首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java线程有"join()“来等待所有线程,那么我们需要什么用例CyclicBarrier呢?

Java线程有"join()“来等待所有线程,那么我们需要什么用例CyclicBarrier呢?
EN

Stack Overflow用户
提问于 2022-06-18 02:32:35
回答 1查看 58关注 0票数 1

JDK博士说:

代码语言:javascript
复制
public class CyclicBarrier
extends Object

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.
A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.

然后给出一个示例代码,它可以工作。

代码语言:javascript
复制
class Worker implements Runnable {
     int myRow;
     Worker(int row) { myRow = row; }
     public void run() {
       while (!done()) {
         processRow(myRow);

         try {
           barrier.await();
         } catch (InterruptedException ex) {
...
class Solver
...
     List<Thread> threads = new ArrayList<Thread>(N);
     for (int i = 0; i < N; i++) {
       Thread thread = new Thread(new Worker(i));
       threads.add(thread);
       thread.start();
     }

     // wait until done
     for (Thread thread : threads)
       thread.join(); // here we still need to wait all threads using join()
...

但是CyclicBarrier在我看来仍然是多余的:线程“互相等待”,这是由调用thread.join()for循环完成的。

无论如何,只要我希望收集线程的所有结果,我就必须等待它们完成,对吗?如果Thread.join()有效,那么为什么或者在什么情况下我们需要引入CyclicBarrier(OCAM剃刀?)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-18 05:14:30

用于线程的Javadoc打电话给join()

等待这个线程死掉。

如果您有一些线程比“开始”和“完成”更有趣,那么您也许可以使用join()来等待它们全部完成。

来自用于CyclicBarrier的Javadoc

CyclicBarriers在涉及固定大小线程的程序中非常有用,这些线程必须偶尔等待对方。

在许多场景中,您希望在线程本身之间定义更有趣或更依赖的交互,而“等待线程死亡”的场景不能提供足够的控制。

java.util.concurrent包中还有许多其他有用的东西,如相位器CountDownLatch。因此,您可能不需要任何这些(目前),但它们可能非常有用。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72666297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档