有三个线程在第4个线程上等待,后者发出通知,所有等待的线程都被唤醒.
这是源代码:
class Reader extends Thread {
Calculator calc;
public Reader(Calculator calc) {
this.calc = calc;
}
public void run() {
synchronized(calc) {
try {
System.out.println(Thread.currentThread().getName() + " waiting for calc");
calc.wait();
} catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(Thread.currentThread().getName() + " Total is: " + calc.total);
}
}
}
class Calculator extends Thread {
public int total = 0;
public void run() {
synchronized(this) {
for (int i = 0; i < 50; i++) {
total += i;
}
notify();
System.out.println("I notified a thread");
}
}
}
public class Notify {
public static void main(String[] args) {
Calculator calc = new Calculator();
Reader r1 = new Reader(calc);
Reader r2 = new Reader(calc);
Reader r3 = new Reader(calc);
r1.start();
r2.start();
r3.start();
calc.start();
}
}
这是我得到的输出:
Thread-2 waiting for calc
Thread-4 waiting for calc
Thread-3 waiting for calc
I notified a thread
Thread-2 Total is: 1225
Thread-3 Total is: 1225
Thread-4 Total is: 1225
不应该只唤醒一个等待线程并执行System.out.println(Thread.currentThread().getName()“Total is:”calc.total);指导?