CountDownLatch:一般是阻塞主线程,等待其他子线程全部完成后,再继续执行主线程。调用 latch.await() 方法的线程处于阻塞状态,latch.countDown() 达到一定的次数就会唤醒被阻塞的线程。
CyclicBarrier:调用 barrier.await() 方法的线程处于阻塞状态、相互等待,barrier.await() 方法被调用达到一定的数量后,被阻塞的线程一起执行任务。
下面是CountDownLatch和CyclicBarrier组合使用,模拟并发:
public class CountDownLatchAndCyclicBarrier extends Thread {
private CyclicBarrier barrier;
private CountDownLatch latch;
private static int num;
CountDownLatchAndCyclicBarrier(CyclicBarrier barrier, CountDownLatch latch) {
this.barrier = barrier;
this.latch = latch;
}
@Override
public void run() {
try {
barrier.await(); // 创建好的线程都会在此阻塞、直到 barrier.await() 被调用20次
for (int i = 0; i < 10000; i++) {
add();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
latch.countDown(); // 所有线程都执行完此方法,主线程才能被唤醒
}
}
// 有【static】是类锁、所有线程共享一把锁;没有【static】是对象锁、一个对象一把锁、不安全,感兴趣的人可以去掉试试看。
private static synchronized void add() {
num++;
}
public static void main(String[] args) throws Exception {
int count = 20;
CyclicBarrier barrier = new CyclicBarrier(count);
CountDownLatch latch = new CountDownLatch(count);
for (int i = 0; i < count; i++) {
new CountDownLatchAndCyclicBarrier(barrier, latch).start();;
}
latch.await(); // 阻塞主线程,等待20个线程全部结束
System.out.println(CountDownLatchAndCyclicBarrier.num);
}
}
下面是CyclicBarrier模拟运动员准备、起跑、结束的过程:
public class CyclicBarrierTest {
public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
ExecutorService executor = Executors.newFixedThreadPool(3);
CyclicBarrier start = new CyclicBarrier(3); // 三个选手,三个起跑栅栏
CyclicBarrier end = new CyclicBarrier(4); // 三个选手栅栏 + 一个结束标志栅栏
while (true) {
executor.execute(new Player(start, end, "张三"));
executor.execute(new Player(start, end, "李四"));
executor.execute(new Player(start, end, "王五"));
end.await();
System.out.println("比赛结束==================================");
}
}
}
public class Player extends Thread {
private CyclicBarrier start;
private CyclicBarrier end;
private String name;
public Player(CyclicBarrier start, CyclicBarrier end, String name) {
this.start = start;
this.end = end;
this.name = name;
}
@Override
public void run() {
try {
int a = new Random().nextInt(5) + 1;
System.out.println(this.name + " 准备耗时: " + a + "s");
Thread.sleep(a * 1000);
System.out.println(this.name + " 准备好了。。。 等待其他人。。。");
this.start.await();
System.out.println(this.name + " 开始起跑。。。go go go");
int b = new Random().nextInt(5) + 2;
Thread.sleep(b * 1000);
System.out.println(this.name + " 到达终点!!! 耗时: " + b + "s");
this.end.await();
} catch (Exception e) {
e.printStackTrace();
}
}
}