Java: Producer/Consumer using BlockingQueue: having the consumer thread wait() until another object is queued

不羁的心 提交于 2019-12-04 20:46:52

The point of BlockingQueue is that you don't have to write this code yourself.

Just call take() instead, which will wait until an object is inserted onto the queue, or use poll but with a timeout, so that it only returns null if the timeout elapses.

EDIT: Just to clarify the answer - as it's in the comments - not only does this mean you can remove the wait/notify code; you also remove the size check as the queue does that for you.

Just to add on what's been said, it's important to note the difference between put() and add(). If your queue is full, points you try and insert may never actually be inserted in the queue, because an IllegalStateException will be thrown, while put() will wait, if necessary, to insert the point.

Documentation for add() states

Adds the specified element to this queue if it is possible to do so immediately, returning true upon success, else throwing an IllegalStateException.

while put states

Adds the specified element to this queue, waiting if necessary for space to become available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!