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<100 ; i++){
total += i;
}
notify();
}
}
}
As the example above, if wait()
block enter first, the subsequent notify()
in ThreadB will tell the Main Thread to continue.
But we cannot guarantee wait()
will execute before notify(
), what if ThreadB enter the block first? Notify()
will execute before wait()
, so wait()
will hang there forever (because no more notify()
to tell it to continue)? What usually is the proper way to handle this?