我找不到为什么 ThreadA 仅在 ThreadB 完全完成它的工作时才从 ThreadB 收到通知的原因。如果我评论 notify() ThreadA 无论如何都会收到通知。
ThreadB 完成工作后会自动发送通知吗?
为什么 ThreadB 没有按时通知 ThreadA?
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();
System.out.println("waiting done");
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
}
}
}
class ThreadB extends Thread {
int total=0;
public void run() {
synchronized(this)
{
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getName()+" "+ Integer.toString(i));
total += i;
}
notify();
System.out.println("notify done");
for(int i=0;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+ Integer.toString(i));
total += i;
}
}
}
}
输出:
Waiting for b to complete...
Thread-0 0
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-0 5
Thread-0 6
Thread-0 7
Thread-0 8
Thread-0 9
notify done
Thread-0 0
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-0 5
Thread-0 6
Thread-0 7
Thread-0 8
Thread-0 9
Thread-0 10
Thread-0 11
Thread-0 12
Thread-0 13
Thread-0 14
Thread-0 15
Thread-0 16
Thread-0 17
Thread-0 18
Thread-0 19
waiting done
Total is: 235
附加问题 - 为什么 Total 输出为 235?