我是线程和学习的新手,但是在下面的代码中,为什么notify不起作用。根据我的理解,当i = 5时,notify应该执行主线程并打印总数。如果我错了,请纠正。
public class ThreadA {
public static void main(String[] args){
ThreadB b = new ThreadB();
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: " + b.total);
}
}
}
class ThreadB extends Thread{
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<10 ; i++){
total += i;
if(i==5){
System.out.println("Notify");
notify();
}
System.out.println("Total is in cal thread: "+i+":" + total);
}
}
}
}
这是程序的输出:
Waiting for b to complete...
Total is in cal thread: 0:0
Total is in cal thread: 1:1
Total is in cal thread: 2:3
Total is in cal thread: 3:6
Total is in cal thread: 4:10
Notify
Total is in cal thread: 5:15
Total is in cal thread: 6:21
Total is in cal thread: 7:28
Total is in cal thread: 8:36
Total is in cal thread: 9:45
Total is: 45 –
最佳答案
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();
调用
notify
仅影响当前正在等待的线程,在调用之后开始等待的线程将不受影响。在您可以100%确认同步块内尚未等待的事情之前,请不要调用wait
。