gpt4 book ai didi

java - CyclicBarrier 重用示例

转载 作者:行者123 更新时间:2023-12-01 12:07:18 24 4
gpt4 key购买 nike

在这种情况下,CyclicBarrier 是否最适合。
我想在 Stages 中并行运行 n 个线程(在 Stages 等待直到所有线程完成该 Stage)。

        public class CyclicBarr {


public static void main(String[] args) {


CyclicBarrier barrier = new CyclicBarrier(3, new Runnable() {
private int count =1;
@Override
public void run() {
System.out.println("Completed..!! "+(count++));
}
});

for (int i = 1; i <= 3; i++) {

Thread t = new Thread(new CuclicBarThread(barrier));
t.start();

}



}
}

线程是
        public class CuclicBarThread implements Runnable {

CyclicBarrier barrier;

public CuclicBarThread(CyclicBarrier barrier) {
this.barrier = barrier;
}

@Override
public void run() {
try {
for (int i = 1; i < 5; i++) {
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 1 After Stage 1 Completed");
barrier.await();

for (int i = 1; i < 5; i++) {
Thread.sleep(1000);
}
System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 2 After Stage 2 Completed");
barrier.await();

for (int i = 1; i < 5; i++) {
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " :: Waiting At Barrier 3 After Stage 3 Completed");
barrier.await();
System.out.println(Thread.currentThread().getName()+" :: $$$$$$$$ Completed $$$$$$$$");
} catch (Exception ex) {
ex.printStackTrace();
}



}
}

最佳答案

是的,它是可重复使用的。这就是为什么它被称为“循环”。这是其 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.



你对 CyclicBarrier 的使用对我来说似乎很好。

关于java - CyclicBarrier 重用示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32502435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com