CyclicBarrier使用案例
/**
* CyclicBarrier使用案例,线程执行任务完成后会停留在await(),
* 直到所有线程执行任务完毕,才会被放行;
* 接着就会继续执行其他的任务
*/
public class CyclicBarrierExample {
public static void main(String[] args) {
int numThreads = 3;
CyclicBarrier barrier = new CyclicBarrier(numThreads, () -> {
System.out.println("All threads have reached the barrier. Starting the next phase.");
});
for (int i = 0; i < numThreads; i++) {
Thread worker = new Thread(new Worker(barrier, "Worker-" + i));
worker.start();
}
}
static class Worker implements Runnable {
private CyclicBarrier barrier;
private String workerName;
public Worker(CyclicBarrier barrier, String workerName) {
this.barrier = barrier;
this.workerName = workerName;
}
@Override
public void run() {
System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")) + " Worker " + workerName + " is working");
try {
Thread.sleep((long) (Math.random() * 2000)); // 模拟不同的工作时间
System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")) + " Worker " + workerName + " has reached the barrier");
barrier.await(); // 等待所有线程到达屏障
System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")) + " Worker " + workerName + " is continuing to work");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
输出结果
12:45:40 Worker Worker-1 is working
12:45:40 Worker Worker-2 is working
12:45:40 Worker Worker-0 is working
12:45:40 Worker Worker-0 has reached the barrier
12:45:40 Worker Worker-1 has reached the barrier
12:45:42 Worker Worker-2 has reached the barrier
All threads have reached the barrier. Starting the next phase.
12:45:42 Worker Worker-2 is continuing to work
12:45:42 Worker Worker-0 is continuing to work
12:45:42 Worker Worker-1 is continuing to work
Process finished with exit code 0