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();
}
}}
I am unable to understand the code flow and how run method is being called in the above programs.
When the object is of class ThreadB then why main() thread of ThreadA is able to synchronize object b. Apart from that when wait() is encountered by the main() thread, how the executions shifts to run() in ThreadB.
Your program has a race condition.
After
main()callsb.start()there are two threads running, unsynchronized, and they race to lock (i.e., synchronize on) thebobject. There is no way to predict which thread will lock it first.If the
main()thread locks it first, then it will callb.wait(). That will temporarily unlock thebobject, and allow the other thread to run. The other thread will do its work, callb.notify()and exit thesynchronizedblock. As soon as it exits, themain()thread will be able to return from thewait()call.If the second thread is first to lock the
bobject, the behavior will be different: It will do its work, callnotify(), and return. But thenotify()call will do nothing in that case because themain()thread will be blocked trying to enter thesynchronizedblock. It won't be waiting in theb.wait()call, andnotify()doesn't do anything if there isn't any other thread waiting.So what will happen next in that case is, when the
ThreadBthread leaves thesynchronizedblock, themain()thread will be able to enter it and callwait(). The program will hang at that point because theThreadBthread has already finished its work and died. There's no other thread left to callnotify().We call it a race condition when two (or more) threads race to do something, and the output of the program depends on which one gets there first.