我有一个调用该wait方法的线程,只有当notify从其他类调用该方法时才能唤醒:
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) {}
System.out.println("Total is: " + b.total);
}
}
}
class ThreadB extends Thread {
int total;
public void run() {
synchronized(this) {
for(int i=0;i<100;i++) {
total += i;
}
notify();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码synchronized中main,如果块中,如果ThreadA不执行第一个而不是另一个同步块执行并完成,则ThreadA执行其synchronized块和调用wait …