1) In Bob, you are synchronizing on the Object sagetThread, the instance of Thread running a Saget runnable. In Saget you synchronize and notify on this, an instance of Saget. The instance of Saget is not the same Object as sagetThread, so you are neither synchronizing with, nor notifying Bob from Saget. You would have to synchronize on sagetThread in Saget, and call sagetThread.notify() to communicate properly.
2) In Saget, you first gain the synchronized lock, then call sleep, mistakenly believing this would give Bob time to get to wait(). The problem is that sleep does NOT give up the synchronized lock, so if Bob was synchronized on the same object as Saget, then, if Saget gets the synchronize lock first, Bob could not ever get to wait() until after the notify() is called. In this scenario, even if properly synchronized on the same object, Bob could not start up again until after the sagetThread came to an end.
This is one possible scenario you have to watch for:
To fix this problem you should move the first sleep() in Saget before the synchronize().
Steve, thank you very much! I had beat around on this a couple hours trying to figure it out myself. So close! I think I see what you mean 'this' was the runnable class, not the thread class. I see that now!
One question. Do I even need the first sleep? The one you instructed to move before synchonized? My thought was that it is possible for saget to run before bob, then when bob runs the wait would be forever???
I am going to keep writing thread code until I 'get it', so don't be surprised if I come back for help.
Glad I could help. Just keep on practicing and you will get it.
John Nobles wrote:One question. Do I even need the first sleep? The one you instructed to move before synchonized? My thought was that it is possible for saget to run before bob, then when bob runs the wait would be forever???
Yes you will need the sleep. As you said, there is a chance that Saget will start before Bob. To protect against that you will need to do something to make sure Bob gets the lock and calls wait() first. For these simple tests calling a sleep in the thread you want to kick off second is usually good enough.
Legend has it that if you rub the right tiny ad, a genie comes out.
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth