I don't understand why Thread t is not coming out of wait.
Looks like the notifyAll has been invoked corrcetly.
here is the code
It prints "Ready to print, Now prining," and then hangs. I thought I understand this but not anymore.
Please clarify why thread t is waiting forever...What has to be done to bring t out of wait.
Thread object you may not get the results you expect.
I will try to explain here-
Producer and Consumer is a classic example however to make it interesting consider following scenario below
We have a Bar Object and 3 working thread (2 bar tender and 1 helper)
Object Bar has 2 methods getGlass and putGlass and List of glasses. When a bar tender wants a glass it will call getGlass method of bar object and helper calls putGlass to place a glass on shelf.
Each time getGlass is called a glass is subtracted from list similarly each time put is called glass is added to List.
Now when list becomes empty and there are no glasses in the bar then any bar tender that calls getGlass would be asked to wait. And when helper thread calls putGlass then all bar tender thread gets notified as they are waiting. You can assume that the notifying mechanism is internal to restaurant(jvm )
For your example, the right way would be-
hope it helps
I understand this question and the solution to it. As the wait and notify are not both working on the same objects Lock. However , I have the same question as daniele... is it not possible that inside run() the JVM decides to switch threads and starts executing main thread before "Ready to Print" gets executed....therefore producing the output...
"Now Printing," first???
daniele ippoliti wrote:sorry but the question says: which kind of output produce the code...and also if the probability are 99,9% that this code produce Ready to print,Now printing for sleep time values, there is the 0,01% of probability that output is Now printing,Ready to print...so the answer "output is Ready to print,Now printing" is wrong!!! is it right my observation???
It's an interesting point. It is *theoretically* possible for the code to produce the output (not 0.01%), but in reality, the probability is likely zero. For the output to happen, you would need a JVM that can't schedule a running thread within a half second. You really need something extreme for that to happen.
But yes, you are right.... it is theoretically possible, as there is nothing in the specification that will prevent it from happening.