I have a thread that calls the wait
method and can only be awoken when the notify
method called from some other class:
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();
}
}
}
In the above code if the synchronized
block in main
, if the ThreadA
does not execute first and instead the other synchronization block executing and completes to completion, then ThreadA
executes its synchronized
block and calls wait
, what is going to happen and how it will be notified again?
Why to make that complex ? Just use join() function of Thread.