/** * * @描述: 同步工具 * 表示你們彼此等待,你們集合好後纔開始出發,分散活動後又在指點地點集合碰合 . * @做者: Wnj . * @建立時間: 2017年5月16日 . * @版本: 1.0 . */ public class CyclicBarrierTest { public static void main(String[] args) { ExecutorService service = Executors.newCachedThreadPool(); //要有三個線程到了才走 final CyclicBarrier cb = new CyclicBarrier(3); for (int i = 0; i < 3; i++) { Runnable runnable = new Runnable() { public void run() { try { Thread.sleep((long)(Math.random() * 10000)); System.out.println("線程" + Thread.currentThread().getName() + "即將到達集合地點1,當前已有" + (cb.getNumberWaiting() + 1) + "個已經到達," + (cb.getNumberWaiting() == 2 ? "都到齊了,繼續走啊" : "正在等候")); //三個線程的第N個線程等待 cb.await(); Thread.sleep((long)(Math.random() * 10000)); System.out.println("線程" + Thread.currentThread().getName() + "即將到達集合地點2,當前已有" + (cb.getNumberWaiting() + 1) + "個已經到達," + (cb.getNumberWaiting() == 2 ? "都到齊了,繼續走啊" : "正在等候")); //三個線程的第N個線程等待 cb.await(); Thread.sleep((long)(Math.random() * 10000)); System.out.println("線程" + Thread.currentThread().getName() + "即將到達集合地點3,當前已有" + (cb.getNumberWaiting() + 1) + "個已經到達," + (cb.getNumberWaiting() == 2 ? "都到齊了,繼續走啊" : "正在等候")); //三個線程的第N個線程等待 cb.await(); } catch (Exception e) { e.printStackTrace(); } } }; service.execute(runnable); } service.shutdown(); } }