用共享对象发信号

时间:2014-03-03 14:27:21

标签: java multithreading

我无法理解,在何处放置方法

hasDataToProcess()& MySignal类的setHasDataToProcess(),

在App9类中维护NotThreadSafe类型对象的同步。

请帮助我知道这个地方!!!

//通过共享对象发送信号

代码:

class MySignal{
    protected boolean hasDataToProcess = false;

    public synchronized boolean hasDataToProcess(){
        return this.hasDataToProcess;
    }
    public synchronized void setHasDataToProcess(boolean hasData){
        this.hasDataToProcess = true;
    }
}

class NotThreadSafe{
    StringBuilder builder = new StringBuilder();
    public void add(String text){
        this.builder.append(text);
    }
    public void display(){
        System.out.println(builder);
    }
}

public class App9 extends Thread {
    NotThreadSafe instance;
    protected MySignal sharedSignal = new MySignal();
    public App9(NotThreadSafe sharedInstance){
        this.instance = sharedInstance;
    }
    @Override
    public void run(){
        this.instance.add("sham");
        this.instance.display();
    }

    public static void main(String[] args) {
        NotThreadSafe sharedInstance = new NotThreadSafe();
        for(int i=0; i<10 ; i++){
            Thread t = new App9(sharedInstance);
            t.start();
        }
    }
}

0 个答案:

没有答案