Can you please tell me what is wrong in this code. I am trying to implement producer consumer problem.
Well, there are actually two *major* problems with this code.
The first is the synchronization. When you have producers and consumers trying to send notifications to each other, you need to make sure that notifications are not lost. If you look at your code, the while loop is actually outside of synchronization. This means that there are two points where you give up the lock. If the notification is sent while the thread is in the wait(), then fine. However, if all the consumers are at the top/bottom of the loop, where it is not synchronized, then that notification from the producer will be lost.
The second problem, and the reason you are getting the "current thread not owner" problem, is the object you are synchronizing on. Synchronization is with objects, not references. You have to synchronize on the same object. And autoboxing uses different objects when you increment / decrement an integer.
Henry [ June 19, 2007: Message edited by: Henry Wong ]
There are also two *minor* problems with the code.
First, you are only checking to see if the buffer is within range *before* you wait(). You need to do that after the wait too -- as it is possible to get notifications for conditions that have already been taken. This can be solved by changing the "if" to a "while".
Second, you are using the lock to wait for 2 possible condtions -- this is why you have to use notifyAll(), as you can't control who will get the notification. This is incredibly wasteful. I would recommnend using the ReentrantLock class instead, as it can have two different condition variables bound to it -- one for each waiting condition. This will allow you to wakeup only one thread to resolve the condition.