The only thread that uses ock.notifyAll (); is main thread who sleeps for 3000.Why synchronized is used here?
synchronized (lock) {
lock.notifyAll ();
}
Although, only the main thread call lock.notifyAll(), but all 4 threads (including main) uses the lock object. Whenever any thread access a shared object, it is only safe to synchronized them. Because we don't know what the method do to the attributes within the shared object
That is because you have change the MyThread.run to wait on each thread objects themselves. After which, nothing is going the notify them to wake up :0)..
In the original implementation, all of the MyThread instances are waiting on the same lock object, and the main thread will wake all of them up to print the "after wait" statement.
Did you actually get that code from the Javaworld website?
I think you are correct in your understanding. I think the reason the main thread calls the notifyAll method is because the main thread is deciding when they should be woken, ie after the 3000ms wait.