CountdownLatch和CyclicBarrier
CountDownLatch:
具有计数器的功能,等待其他线程执行完毕,主线程在继续执行,用于监听某些初始化操作,并且线程进行阻塞,等初始化执行完毕后,通知主线程继续工作执行
CyclicBarrier:
所有线程在其他线程没有准备好之前都在被阻塞中,等到所有线程都准备好了才继续执行。
区别:
CountDownLatch: 一个线程(或者多个), 等待另外N个线程完成某个事情之后才能执行。
CyclicBrrier: N个线程相互等待,任何一个线程完成之前,所有的线程都必须等待。
举例:
CountDownLatch
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
//lambda中只能只用final的变量
final int times = i;
new Thread(() -> {
try {
System.out.println("子线程" + Thread.currentThread().getName() + "正在赶路");
Thread.sleep(1000 * times);
System.out.println("子线程" + Thread.currentThread().getName() + "到公司了");
//调用latch的countDown方法使计数器-1
latch.countDown();
System.out.println("子线程" + Thread.currentThread().getName() + "开始工作");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
try {
System.out.println("门卫等待员工上班中...");
//主线程阻塞等待计数器归零
latch.await();
System.out.println("员工都来了,门卫去休息了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
CyclicBarrier:
public static void main(String[] args) {
final CyclicBarrier cyclicBarrier = new CyclicBarrier(10,()->{
System.out.println("所有人都准备好了裁判开始了");
});
for (int i = 0; i < 10; i++) {
//lambda中只能只用final的变量
final int times = i;
new Thread(() -> {
try {
System.out.println("子线程" + Thread.currentThread().getName() + "正在准备");
Thread.sleep(1000 * times);
System.out.println("子线程" + Thread.currentThread().getName() + "准备好了");
cyclicBarrier.await();
System.out.println("子线程" + Thread.currentThread().getName() + "开始跑了");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}