Java线程等待和通知

我有两个线程.线程 A 正在从队列中提取一些元素,线程 B 正在向队列中添加一些元素.

I have two threads. Thread A is pulling some elements from queue and thread B is adding some elements to the queue.

我希望线程 A 在队列为空时进入睡眠状态.

I want thread A to go to sleep when the queue is empty.

当线程 B 向队列中添加一些元素时,它应该确保线程 A 正在工作.如何在 Java 中做到这一点?

When thread B adds some element to the queue it should make sure that thread A is working. How can this be done in Java?

推荐答案

使用 BlockingQueue,即:

一个队列,它还支持在检索元素时等待队列变为非空的操作,以及在存储元素时等待队列中可用空间的操作.

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

说真的,不要试图在这里重新发明轮子.




(如果您必须使用等待/通知,请阅读 本教程.但请不要痛苦!)

Seriously, don't try to reinvent the wheel here.




(If you must use wait/notify, read this tutorial. But spare yourself the pain, please!)

相关文章