I was wondering that myself. Here is my thought. Since the System.out.println method is called outside of the synchronized method put or get, it may call them in a different order. So the first thing it does is call the put method, creates the lock, puts the value, notifies get, and then releases the lock. Now that it is realeased, get can start, doing it's thing. But since the print statement is outside of the put and get methods, it will depend on the scheduler on which thread will call the print method first. If we changed this code and put the print statement inside of the put and get synch methods, it would always write them in order: Producer #5: put 1 Consmer #5: get 1 In order to do that you will have to change the construtor for the CubbyHole class and pass in a value. But you get the idea. [This message has been edited by bill bozeman (edited October 18, 2000).]
You are right. When you say wait() in a method, this has to be in a synchronzied method or block. Since it is synchronized, that means there was a lock on the object. When you say wait(), you are telling the JVM that you want to release this lock and let other threads take over the lock. You combine this with a boolean flag so that you do not start your method again, until whatever else you needed to happen does and then you notify() your other thread that it can start again.
Did you miss me? Did you miss this tiny ad?
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop