简体   繁体   English

Java并发 - 离开方法后重置条件

[英]Java concurrency - reset condition after leaving method

I am trying to figure out a solution to the following problem: 我试图找出以下问题的解决方案:

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

}

The issue I am facing seems to be simple, but I am struggling to see how all the edge cases can be captured. 我面临的问题似乎很简单,但我很难看到如何捕获所有边缘情况。

One solution might be to use Lock s with Condition s, then all threads witing on waitOnCondition are going to await until a flag is set to true and then proceed, for example. 一种解决方案可能是使用带有ConditionLock ,然后awaitwaitOnCondition上的所有线程将await直到标志设置为true然后继续,例如。 The thread executing signal() would then use the same lock, set the flag to true and signal . 执行signal()的线程然后将使用相同的锁,将标志设置为true并signal Then, the released threads would reacquire the lock to set the condition to false. 然后,释放的线程将重新获取锁以将条件设​​置为false。 This, however, does not guarantee that all the threads are going to reach the getValue point. 但是,这并不能保证所有线程都将到达getValue点。 For instance: 例如:

Thread 1 and 2 are waiting, get the signal. 线程1和2正在等待,获得信号。 After being signalled, thread 1 reacquires the lock, checks the condition, now true, and proceeds. 在发出信号后,线程1重新获取锁定,检查条件,现在为真,然后继续。 gets the value, acquires the lock and sets condition to false. 获取值,获取锁并将条件设置为false。 Thread 2, now sees the condition still as false, and blocks again. 线程2现在看到条件仍为false,并再次阻塞。

Another solution, quite neat and elegant, would be to use a CountDownLatch . 另一个非常整洁和优雅的解决方案是使用CountDownLatch This guarantees that all the threads are going to proceed. 这保证了所有线程都将继续。 This is, however, not resettable. 但是,这不可重置。 Any other ideas or comments? 还有其他想法或意见吗?

Seems like CyclicBarrier is what you need. 看起来像CyclicBarrier就是你所需要的。 It is resettable and also allows to trigger a barrier action when all parties are there. 它是可重置的,并且当所有各方都在那里时也允许触发屏障动作。

There is also Phaser which is an advanced version of CyclicBarrier and it requires JDK 7 to run. Phaser也是CyclicBarrier的高级版本,它需要运行JDK 7。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM