Java: How can a thread wait on multiple objects?

后端 未结 8 2148
有刺的猬
有刺的猬 2020-12-30 23:46

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

But what if a threa

8条回答
  •  感情败类
    2020-12-31 00:45

    It appears that in your case you're waiting for "notifications" from two different sources. You may not have to "wait" (as in normal java synchronized(object) object.wait()) on those two objects per se, but have them both talk to a queue or what not (as the other answers mention, some blocking collection like LinkedBlockingQueue).

    If you really want to "wait" on two different java objects, you might be able to do so by applying some of the principles from this answer: https://stackoverflow.com/a/31885029/32453 (basically new up a thread each to do a wait on each of the objects you're waiting for, have them notify the main thread when the object itself is notified) but it might not be easy to manage the synchronized aspects.

提交回复
热议问题