我正在阅读以下链接中的 CyclicBarrier
http://java-latte.blogspot.in/2013/10/cyclicbarrier-in-java-concurrency.html .
在示例 1 中,CyclicRaceDemo.java
main 方法中,CyclicBarrier 被重用,没有调用 reset 方法。
我运行了这个例子,它运行良好。所以,我想知道 reset
方法有什么用。应该什么时候调用?还是我们根本不需要调用它?
最佳答案
CyclicBarrier
是循环的,因为它可以在不重置的情况下重复使用。来自Javadoc
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
所以在正常使用中,一旦所有线程都被收集并且屏障被打破,它会自行重置并可以再次使用。
Resets the barrier to its initial state. If any parties are currently waiting at the barrier, they will return with a
BrokenBarrierException
. Note that resets after a breakage has occurred for other reasons can be complicated to carry out; threads need to re-synchronize in some other way, and choose one to perform the reset. It may be preferable to instead create a new barrier for subsequent use.
所以 reset
会导致任何当前等待的线程抛出 BrokenBarrierException
并立即唤醒。 reset
用于“打破”障碍。
另请注意:一旦线程被强制唤醒,再次同步它们就很棘手了。
TL;DR:在正常情况下,您永远不需要使用 reset()
。
关于java - 何时在 java 多线程中重置 CyclicBarrier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24104642/