Проблема в том, что разбудит этот поток? То есть, как вы гарантируете, что другой поток не вызовет foo.notify()перед вызовами первого потока foo.wait()? Это важно, потому что объект foo не запомнит, что он был уведомлен, если вызов notify произойдет первым. Если есть только одно уведомление (), и если это происходит до wait() , то wait() никогда не вернется.
Вот как предполагалось использовать wait и notify:
voidconsumeSomething(...) { Productp=null; synchronized(lock) { while (q.peek() == null) { lock.wait(); } p = q.remove(); } reallyConsume(p); }
The most important things to to note in this example are that there is an explicit test for the condition (i.e., q.peek() != null), and that nobody changes the condition without locking the lock.
If the consumer is called first, then it will find the queue empty, and it will wait. There is no moment when the producer can slip in, add a Product to the queue, and then notify the lock until the consumer is ready to receive that notification.
On the other hand, if the producer is called first, then the consumer is guaranteed not to call wait().
The loop in the consumer is important for two reasons: One is that, if there is more than one consumer thread, then it is possible for one consumer to receive a notification, but then another consumer sneaks in and steals the Product from the queue. The only reasonable thing for the fist consumer to do in that case is wait again for the next Product. The other reason that the loop is important is that the Javadoc says Object.wait() is allowed to return even when the object has not been notified. That is called a "spurious wakeup", and the correct way to handle it is to go back and wait again.
Also note: The lock is private and the queue is private. That guarantees that no other compilation unit is going to interfere with the synchronization in this compilation unit.
And note: The lock is a different object from the queue itself. That guarantees that synchronization in this compilation unit will not interfere with whatever synchronization that the Queue implementation does (if any).
NOTE: My example re-invents a wheel to prove a point. In real code, you would use the put() and take() methods of an ArrayBlockingQueue which would take care of all of the waiting and notifying for you.
Ответ 2
You can only wait on an object if you already hold the lock on it, you could try:
Note, I added an exit condition to your thread so it will actually stop (as is, your thread will keep going). You'd probably want to make the exit condition private and add a setter for cleanliness. Also, I'm using join to properly wait for your thread to complete.