何时在Java多线程中重置CyclicBarrier [英] When to reset CyclicBarrier in java multithreading
问题描述
我在以下链接中正在阅读CyclicBarrier
http://java-latte.blogspot.in/2013/10/cyclicbarrier- in-java-concurrency.html .
I was reading CyclicBarrier
in the following link
http://java-latte.blogspot.in/2013/10/cyclicbarrier-in-java-concurrency.html.
在示例1 CyclicRaceDemo.java
主要方法中,无需调用 reset 方法即可重用CyclicBarrier.
In the example 1, CyclicRaceDemo.java
main method, CyclicBarrier is being reused without calling reset method.
我运行了该示例,它运行良好.因此,我想知道reset
方法的用途是什么.什么时候应该叫它?还是我们完全需要调用它?
I ran the example and it worked fine. So, I am wondering what's the use of reset
method. When should it be called? Or do we need to call it at all?
推荐答案
CyclicBarrier
是循环的,因为它可以重用而无需重置.从 Javadoc
A CyclicBarrier
is cyclic because it can be reused without resetting. From the Javadoc
一种同步辅助工具,它允许一组线程全部等待 彼此达到共同的障碍点. CyclicBarriers是有用的 在涉及固定大小线程的程序中, 偶尔互相等待.该障碍称为循环,因为 可以在释放等待线程之后重新使用它.
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.
因此,在正常使用情况下,一旦所有线程都被收集并且隔离栅被破坏,它将重置自身并可以再次使用.
So in normal usage, once all the threads are collected and the barrier is broken, it resets itself and can be used again.
将屏障重置为其初始状态.如果当前有任何参与者 在障碍处等待,他们将带着
BrokenBarrierException
.请注意,发生破损后会重置 由于其他原因,执行起来可能很复杂;线程需要 以其他方式重新同步,然后选择一个以执行重置. 相反,最好为以后的操作创建新的障碍. 使用.
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
用于要突破"障碍的情况.
So reset
causes any currently waiting threads to throw a BrokenBarrierException
and wake immediately. reset
is used when you want to "break" the barrier.
还请注意警告-强制唤醒线程后,再次同步它们很棘手.
Note also the caveat - once the threads have been awoken forcibly it's tricky to synchronize them again.
TL; DR :在正常情况下,您永远不需要使用reset()
.
TL;DR: you should never need to use reset()
in normal circumstances.
这篇关于何时在Java多线程中重置CyclicBarrier的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!