java - 何时在 java 多线程中重置 CyclicBarrier

标签 java multithreading concurrency java.util.concurrent cyclicbarrier

我正在阅读以下链接中的 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.

所以在正常使用中,一旦所有线程都被收集并且屏障被打破,它会自行重置并可以再次使用。

来自Javadoc for reset()

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/

相关文章:

java - waitFor 命令不等待

java - 在 Spring Boot 中急切加载单例对象,无需注释

java - "java.lang.OutOfMemoryError"错误是否会导致任何安全问题?

java - int[] 在 Java 和 C++ 之间共享?

java - 多线程JAVA中的静态方法行为

algorithm - 算法应该并行化的一些提示是什么?

java - 在 TopDocs.scoreDocs 循环中删除 Lucene 文档而不使用唯一 id

c++ 程序在不同的机器上显示出非常不同的内存行为

java - 如何用java创建一个聊天客户端

java - 生产者-消费者日志记录服务以不可靠的方式关闭