Java线程等待并通知 [英] Java thread wait and notify
问题描述
我有两个主题。线程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
,即:
一个
Queue
,它还支持在检索元素时等待队列变为非空的操作,并等待空间变为空存储元素时在队列中可用。
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.
说真的,不要试图在这里重新发明轮子。
(如果必须使用wait / notify,请阅读本教程。请多给自己带来痛苦!)
Seriously, don't try to reinvent the wheel here.
(If you must use wait/notify, read this tutorial. But spare yourself the pain, please!)
这篇关于Java线程等待并通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!