I could understand that at label 1, we have used wait(); to prevent ThreadB from finishing or completing the calculation, its stack. And, then we used notify to release the waiting thread and complete the ThreadA.
Please explain the inner details esp synchronisation with object b to call wait() on the object and then how notify() acts.
We have used wait(); to prevent main thread from finishing.
What is happening here:
b.start();
Main thread called this b.start() to start the threadb.
b.wait(); //1
Main thread called wait() on object b.It will release lock from the b and will wait here until any other thread call notify on the same object. So it will wait here for infinite time.
In between threadb's run method is working its task. After completing
its for loop it will call notify, that is actually this.notify() and here this object is the same object on which Main thread is waiting.
public void run()
{
synchronized(this){
for(int i=0; i<100; i++){
total+=i;
}
notify();//this.notify
}
}
When threadb will call this.notify() and Main thread will wake up and wait for lock on the same object, notify() does not release lock, but when
synchronized(this){} block will complete lock will be released by threadb.
Main thread will get the lock on object b again and it will become runnable again, now thread schedular will select it and Main thread will start executing.