我做了这个样本,以了解如何等待通知的作品:等待通知由同一个对象同步不起作用
public class WaitingTest implements Runnable {
Thread b = new Thread();
int total;
public static void main(String[] args){
WaitingTest w = new WaitingTest();
}
public WaitingTest(){
b.start();
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is: " + total);
}
}
@Override
public void run(){
synchronized(b){
for(int i=0; i<100 ; i++){
total += i;
System.out.println(total);
}
b.notify();
}
}
}
但我困在这里小时,我不明白为什么它的不太工作。我的输出应该超过0,但它总是零...我想知道是否它的使用不同的线程,但林不知道真的..我错过了什么?
尝试启动线程=) –
你能告诉我们你认为你的'run'方法应该在哪里执行吗? – Pshemo