我是线程和学习新手,但在下面的代码中为什么通知不起作用。根据我的理解,当 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
仅影响当前等待的线程,调用后开始等待的线程不会受到影响。在您可以在同步块(synchronized block)内 100% 确认您正在等待的事情尚未发生之前,请勿调用 wait
。
关于java - Notify() 不能与 Wait() 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24315414/