Java thread wait and notify(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!)
这篇关于Java线程等待和通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java线程等待和通知


- Jersey REST 客户端:发布多部分数据 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01