在下面的代码中,notifyAll()不会改变程序执行中的任何内容。 在我的理解中,wait()条件将等待t1线程完成(完成run()方法)然后继续。
在这种情况下,无论是否有notifyAll(),执行都是相同的。有人可以澄清使用它的区别吗?
我正在使用Java 8.
public class ThreadsTest {
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
Thread t1 = new Thread(thread1, "t1");
t1.start();
synchronized (t1) {
System.out.println("Waiting for t1 to complete");
t1.wait();
System.out.println("Thread t1 finished, result = " + thread1.total);
}
}
}
class Thread1 implements Runnable {
int total;
@Override
public void run() {
synchronized (this) {
for (int i=0 ; i<100; i++) {
total++;
// Below line won't alter anything in program execution
//notifyAll();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
两种情况下的输出都是:
waiting for t1 to complete
t1 finished, result = 100