【发布时间】:2016-06-09 18:41:16
【问题描述】:
我想使用多线程(低级线程),但我遇到了问题。问题是因为至少等待方法将被一个线程调用并且 notifyAll 将被另一个线程调用问题是任何时候我运行程序在我看来 notifyAll 在等待之前被调用所以我“将永远等待”。
我的代码如下:
public class Reader extends Thread {
Calculator c;
public Reader(Calculator cal) {
c=cal;
}
public void run (){
synchronized(c) {
try {
System.out.println("Waiting for calculation");
c.wait();
} catch (InterruptedException ex) {}
System.out.println("Total is:" +c.total);
}
}
public static void main (String[] a) {
Calculator calculator=new Calculator();
new Reader(calculator).start();
new Reader(calculator).start();
new Reader(calculator).start();
new Reader(calculator).start();
new Reader(calculator).start();
}
}
class Calculator implements Runnable {
int total;
public void run() {
synchronized(this) {
for(int i=0;i<100;i++) {
total=total+i;
}
notifyAll();
}
}
}
我在这里得到的输出是连续 5 次等待计算,所以我永远不会达到“总数就是总数”的语句。
我正在尝试找出解决问题的方法,但仍未找到解决方案。如果有人知道该怎么做,我将不胜感激。
提前致谢
【问题讨论】:
标签: java multithreading wait notify