我有产生这样的结果,例如以下2类代码:Java线程同步问题
Wainting for calculation to complete...
Calculator thread says HELLO!
T1 says that total is 10
Wainting for calculation to complete...
Wainting for calculation to complete...
现在线程在等待,但没有人会通知他们。 如何在“计算器线程”唤醒em之前强制T1至T3的线程运行?
public class Calculator implements Runnable{
private int total;
public int getTotal() {
return total;
}
@Override
public void run() {
synchronized (this) {
for (int i = 0; i < 5; i++) {
total += i;
}
System.out.println(Thread.currentThread().getName() + " says HELLO!");
notifyAll();
}
}
}
import static java.lang.System.out;
public class Reader implements Runnable{
private Calculator c;
public Reader(Calculator calc) {
c = calc;
}
public Calculator getCalculator() {
return c;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
Reader read = new Reader(calc);
Thread thread1 = new Thread(read);
Thread thread2 = new Thread(read);
Thread thread3 = new Thread(read);
thread1.setName("T1");
thread2.setName("T2");
thread3.setName("T3");
thread1.start();
thread2.start();
thread3.start();
Thread calcThread = new Thread(read.getCalculator());
calcThread.setName("Calculator thread");
calcThread.start();
}
}
@Override
public void run() {
synchronized (c) {
try {
out.println("Wainting for calculation to complete...");
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
out.println(Thread.currentThread().getName() + " says that " + "total is " + c.getTotal());
}
}
}
我可以在thread3.start()之后添加Thread.sleep(),但我认为这不是一个合适的解决方案。 – nyxz
您不应该使用wait/notify,而应该使用来自java.util.concurrent的调试实用程序,并相应地完全重新设计您的应用程序。目前还不清楚你的真实应用是什么,所以我不能告诉你你应该使用什么。 – toto2
@toto:没有理由不使用wait/notify。他们是简单和灵活的原始人。 java.util.concurrent类只是相同的包装器。我同意更高层次的构造,例如读写锁,这些类提供的障碍和锁闩......但是当一个简单的锤子就足够时,你永远不应该使用铁砧。 –