Java线程等待和通知

Java thread wait and notify(Java线程等待和通知)

本文介绍了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线程等待和通知

基础教程推荐