Reputation: 1
I have this simple code, it's simply a testing case
try
{
synchronized(this) {
while(number != 4)
{
System.out.println("Waiting...");
this.wait();
}
number = 4;
this.notifyAll();
}
}
catch(InterruptedException e)
{}
Of what I know regarding use of the wait() method, once wait is invoked, what comes after should be done. However I can't see to get the wait to end in this case. I have attempted to place a second synchronized block but that doesn't seem to work.
Do you know what could be causing the wait to hang? I looked up deadlocking but that seems to be an entirely different matter.
Upvotes: -2
Views: 532
Reputation: 837
Do you know what could be causing the wait to hang?
You have a loop that's waiting for number
to be set to 4. No code is executed that sets number
to 4. Therefore the loop waits forever.
while(number != 4)
{
System.out.println("Waiting...");
this.wait();
}
/* you can't get here until some other thread sets number to 4. */
number = 4;
this.notifyAll();
}
The wait
call does not terminate until some other code calls notify
, and then when you wake up out of the wait
, you'll loop back again unless number
is now 4.
You can't have a thread simultaneously be in wait
and executing the code that issues the notify
. And if wait
didn't wait, it would not be useful.
Not intending to be rude, but the problem here seems to be a lack of understanding of sequential execution of program code.
Upvotes: 0