Java工作线程模型

时间:2015-12-20 11:09:57

标签: java multithreading worker

我想实现一个工作线程池,它处理输入字符串并处于空闲(无cpu)模式,直到我传递另一个输入字符串。
我为工作人员编写了波纹管代码,但收到错误

public class Worker implements Runnable {

private String data =null;

public void setData(String data) {
    this.data = data;
    notify();
}

@Override
public void run() {
    while (true){
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("data = " + data);
    }
}

并致电

    Worker worker = new Worker();
    Thread thr = new Thread(worker);
    thr.start();
    Thread.sleep(5000);
     worker.setData("11111");
    Thread.sleep(5000);
     worker.setData("2222");

以及如何检查工人是否忙碌 感谢

1 个答案:

答案 0 :(得分:0)

您需要将wait()和notify()调用放在同步块中。

static public class Worker implements Runnable {

    private String data = null;

    public void setData(String data) {
        this.data = data;
        synchronized(this) {
            notify();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                synchronized(this) {
                    wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("data = " + data);
        }
    }
}