package com.smart.thread;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
/**
CyclicBarrier可以在構(gòu)造時指定需要在屏障前執(zhí)行await的個數(shù),所有對await的調(diào)用都會等待枫夺,
直到調(diào)用await的次數(shù)達到預(yù)定指庐完,所有等待都會立即被喚醒杆查。
從使用場景上來說,CyclicBarrier是讓多個線程互相等待某一事件的發(fā)生兔沃,然后同時被喚醒狡逢。
而CountDownLatch是讓某一線程等待多個線程的狀態(tài),然后該線程被喚醒棚亩。
-
Created by jinxiaoyu on 17/4/11.
*/
public class CyclicBarrierDemo {
public static void main(String[] args) throws InterruptedException {
int totalThread = 5;
final CyclicBarrier barrier = new CyclicBarrier(totalThread);for(int i = 0; i < totalThread; i++) { final String threadName = "Thread " + i; new Thread() { @Override public void run() { System.out.println(String.format("%s\t%s %s", new Date(), threadName, " is waiting")); try { barrier.await(); } catch (Exception ex) { ex.printStackTrace(); } System.out.println(String.format("%s\t%s %s", new Date(), threadName, "ended")); } }.start(); }
}
}
Tue Apr 11 21:30:19 CST 2017 Thread 1 is waiting
Tue Apr 11 21:30:19 CST 2017 Thread 0 is waiting
Tue Apr 11 21:30:19 CST 2017 Thread 4 is waiting
Tue Apr 11 21:30:19 CST 2017 Thread 3 is waiting
Tue Apr 11 21:30:19 CST 2017 Thread 2 is waiting
Tue Apr 11 21:30:19 CST 2017 Thread 1 ended
Tue Apr 11 21:30:19 CST 2017 Thread 2 ended
Tue Apr 11 21:30:19 CST 2017 Thread 0 ended
Tue Apr 11 21:30:19 CST 2017 Thread 4 ended
Tue Apr 11 21:30:19 CST 2017 Thread 3 ended