【发布时间】:2013-10-11 11:52:29
【问题描述】:
假设我有两个主要运行的线程 A 和 B,以及一个被异步调用的线程 T。我希望线程 A 等到线程 T 接收到消息 aMsg,线程 B 停止,直到线程接收到消息 msgB T. 我知道如何用 2 个信号灯做到这一点:
sempahoreA = new Sempahore(0);
sempahoreB = new Sempahore(0);
//in thread A
//code until where to run
semaphoreA.acquire()
//in thread B
//code until where to run
semaphoreB.acquire()
//in thread T
if (msgA.equals(msgRecevied)) {
semaphoreA.release()
}
if (msgB.equals(msgReceived)) {
semaphoreB.release()
}
问题是我有多个 A,B,C,... 线程,我不想使用多个信号量。 java.util.concurrent 中是否有一个类可以只用一个实例替换所有信号量?
synchronizer = //?
//in thread A
//code until where to run
synchronizer.acquire(msgA)//only let go if msgA is received from thread calling release
//in thread B
//code until where to run
synchronizer.acquire(msgB)//only let go if msgA is received from thread calling release
//in thread T
if (msgA.equals(msgRecevied)) {
synchronizer.release(msgA)
}
if (msgB.equals(msgReceived)) {
synchronizer.release(msgB)
}//actually here you can call synchronizer.release(msgReceived)
【问题讨论】:
-
我不知道。您可以使用
Lock和多个Conditions,这样会更清晰但不清晰。
标签: java multithreading data-structures concurrency synchronization