CyclicBarrier 和 CountDownLatch 的功能类似,不过CyclicBarrier 是相反的。

  • CyclicBarrier 当线程数达到了这个数目时,所有进入等待状态的线程被唤醒并继续。
  • CountDownLatch 允许一个线程或者多个线程一直等待,直到其他线程完成以后再执行接下来的逻辑。

Example :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierTest {
private static final int THREAD_NUM = 5;
public static class WorkerThread implements Runnable {
CyclicBarrier barrier;
public WorkerThread(CyclicBarrier b) {
this.barrier = b;
}
@Override
public void run() {
try {
System.out.println("Worker's waiting");
barrier.await();//线程在这里等待,直到所有线程都到达barrier。
System.out.println("ID:" + Thread.currentThread().getId() + " Working");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
CyclicBarrier cb = new CyclicBarrier(THREAD_NUM, new Runnable() {
//当所有线程到达barrier时执行
@Override
public void run() {
System.out.println("Inside Barrier");
}
});
for (int i = 0; i < THREAD_NUM; i++) {
new Thread(new WorkerThread(cb)).start();
}
}
}
/*
以下是输出:
Worker's waiting
Worker's waiting
Worker's waiting
Worker's waiting
Worker's waiting
Inside Barrier
ID:12 Working
ID:8 Working
ID:11 Working
ID:9 Working
ID:10 Working
*/