一.CountDownLatch 1:多个线程等待某个线程执行完成时再开始执行,如果用一条黑线表示一个线程的话,如下图:
2:某个线程等待多个线程执行完成时再开始执行,如果用一条黑线表示一个线程的话,如下图:
二.CyclicBarrier
多个线程都完成各自指定逻辑的时候再继续执行剩余逻辑
示例1:
private static void oneWaitMore() throws InterruptedException {
final CountDownLatch countDownLatch=new CountDownLatch(4);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello");
countDownLatch.countDown();
}
}).start();
}
countDownLatch.await();
System.out.println("world");
}
结果1:
hello
hello
hello
hello
hello
world
示例2:
private static void moreWaitone (){
final CountDownLatch countDownLatch=new CountDownLatch(1);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("world");
}
}).start();
}
System.out.println("hello");
countDownLatch.countDown();
}
结果2:
hello
world
world
world
world
world
示例3:
private static void cyclicBarrierTest() {
final CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("world");
}
}).start();
}
}
结果3:
hello
hello
hello
hello
hello
world
world
world
world
world