我正在尝试找出解决以下问题的方法:
public void signal(){
//resets condition and signals threads blocked below
}
public void getValue(){
waitOnCondition(); //block if a condition is not met. When signalled, all threads should proceed and get the value
//get value
resetCondition(); //reset condition, so that the next thread that executes this method blocks on the method above
}
我面临的问题似乎很简单,但我很难看到如何捕获所有边缘情况。
例如,一种解决方案可能是将Lock
s 与Condition
s 一起使用,然后所有线程waitOnCondition
将继续运行,await
直到标志设置为 true,然后继续。然后执行的线程signal()
将使用相同的锁,将标志设置为 true 和signal
。然后,释放的线程将重新获取锁以将条件设置为 false。但是,这并不能保证所有线程都会到达 getValue 点。例如:
线程 1 和 2 正在等待,获取信号。发出信号后,线程 1 重新获取锁,检查条件,现在为真,然后继续。获取值,获取锁并将条件设置为 false。线程 2 现在认为条件仍然为假,并再次阻塞。
另一种非常简洁优雅的解决方案是使用CountDownLatch
. 这保证了所有线程都将继续进行。但是,这是不可重置的。还有其他想法或意见吗?