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.
Before invoke wait()
If it will invoke
wait methodnext step, It means main thread hold monitor of objectbcurrently. And if threadB want to execute run() method it will be blocked for waiting monitor ofbwhich is hold by main thread.invoke wait()
It means
main threadrelease monitor, come into wait status, and advice thread scheduler re_dispatch. Then ThreadB can get monitor and make thing.notify()
after finishing its job, threadB invoke notify() to wake up a single thread that is waiting on this object's monitor, here is main thread. And main thread will go on doing its work.