1.CountDownLatch减计数,CyclicBarrier加计数。
2.CountDownLatch是一次性的,CyclicBarrier可以重用。
然后我们用被大家说烂了的跑步的例子继续说事儿:
1. 有五个人,一个裁判。这五个人同时跑,裁判开始计时,五个人都到终点了,裁判喊停,然后统计这五个人从开始跑到最后一个撞线用了多长时间。
import java.util.concurrent.CountDownLatch; public class Race { public static void main(String[] args) { final int num = 5; final CountDownLatch begin = new CountDownLatch(1); final CountDownLatch end = new CountDownLatch(num); for (int i = 0; i < num; i++) { new Thread(new AWorker(i, begin, end)).start(); } // judge prepare... try { Thread.sleep((long) (Math.random() * 5000)); } catch (InterruptedException e1) { e1.printStackTrace(); } System.out.println("judge say : run !"); begin.countDown(); long startTime = System.currentTimeMillis(); try { end.await(); } catch (InterruptedException e) { e.printStackTrace(); } finally { long endTime = System.currentTimeMillis(); System.out.println("judge say : all arrived !"); System.out.println("spend time: " + (endTime - startTime)); } } } class AWorker implements Runnable { final CountDownLatch begin; final CountDownLatch end; final int id; public AWorker(final int id, final CountDownLatch begin, final CountDownLatch end) { this.id = id; this.begin = begin; this.end = end; } @Override public void run() { try { System.out.println(this.id + " ready !"); begin.await(); // run... Thread.sleep((long) (Math.random() * 10000)); } catch (Throwable e) { e.printStackTrace(); } finally { System.out.println(this.id + " arrived !"); end.countDown(); } } }
CountDownLatch强调的是一个线程(或多个)需要等待另外的n个线程干完某件事情之后才能继续执行。 上述例子,main线程是裁判,5个AWorker是跑步的。运动员先准备,裁判喊跑,运动员才开始跑(这是第一次同步,对应begin)。5个人谁跑到终点了,countdown一下,直到5个人全部到达,裁判喊停(这是第二次同步,对应end),然后算时间。
2. 继续,还是这五个人(这五个人真无聊..),这次没裁判。规定五个人只要都跑到终点了,大家可以喝啤酒。但是,只要有一个人没到终点,就不能喝。 这里也没有要求大家要同时起跑(当然也可以,加latch)。
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class Beer { public static void main(String[] args) { final int count = 5; final CyclicBarrier barrier = new CyclicBarrier(count, new Runnable() { @Override public void run() { System.out.println("drink beer!"); } }); // they do not have to start at the same time... for (int i = 0; i < count; i++) { new Thread(new Worker(i, barrier)).start(); } } } class Worker implements Runnable { final int id; final CyclicBarrier barrier; public Worker(final int id, final CyclicBarrier barrier) { this.id = id; this.barrier = barrier; } @Override public void run() { try { System.out.println(this.id + "starts to run !"); Thread.sleep((long) (Math.random() * 10000)); System.out.println(this.id + "arrived !"); this.barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }
CyclicBarrier强调的是n个线程,大家相互等待,只要有一个没完成,所有人都得等着。正如上例,只有5个人全部跑到终点,大家才能开喝,否则只能全等着。
再强调下,CountDownLatch强调一个线程等多个线程完成某件事情。CyclicBarrier是多个线程互等,等大家都完成。
墨迹完毕...