Java:线程如何等待多个对象? [英] Java: How can a thread wait on multiple objects?

查看:325
本文介绍了Java:线程如何等待多个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个线程可以使用 Object.wait()来阻塞,直到另一个线程调用 notify() notifyAll()关于该对象。

A thread can use Object.wait() to block until another thread calls notify() or notifyAll() on that object.

但是如果一个线程要等到多个对象发出信号?例如,我的线程必须等到 a)字节可用于从 InputStream 读取或b)将项目添加到 ArrayList

But what if a thread wants to wait until one of multiple objects is signaled? For example, my thread must wait until either a) bytes become available to read from an InputStream or b) an item is added to an ArrayList.

线程如何等待这些事件发生?

How can the thread wait for either of these events to occur?

编辑

这个问题涉及等待多个线程完成 - 我的案例涉及一个线程等待多个对象之一单调。

This question deals with waiting for multiple threads to complete -- my case involves a thread waiting for one of many objects to be singnaled.

推荐答案

线程不能一次等待多个对象。

A thread cannot wait on more than one object at a time.

wait() notify()方法是特定于对象的。 wait()方法挂起当前执行的线程,并告诉对象跟踪挂起的线程。 notify()方法告诉对象唤醒它当前正在跟踪的挂起线程。

The wait() and notify() methods are object-specific. The wait() method suspends the current thread of execution, and tells the object to keep track of the suspended thread. The notify() method tells the object to wake up the suspended threads that it is currently keeping track of.

有用链接:一个线程可以在Java(6)中一次调用两个锁上的wait()吗?

这篇关于Java:线程如何等待多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆