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
Queuethat 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线程等待和通知
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
