标签:
1 import java.util.concurrent.CyclicBarrier; 2 import java.util.concurrent.ExecutorService; 3 import java.util.concurrent.Executors; 4 5 /** 6 * CyclicBarrier 7 * 表示大家彼此等待,大家集合好后才开始出发,分散活动后又在指定地点集合碰面, 8 * 这就好比整个公司的人员利用周末时间集合郊游一样,先各自从家出发到公司集合后, 9 * 再同时出发到公园游玩,在指定地点集合后再同时开始就餐。 10 * @author LiTaiQing 11 * 12 */ 13 public class CyclicBarrierTest { 14 public static void main(String[] args) { 15 ExecutorService service = Executors.newCachedThreadPool(); 16 final CyclicBarrier cb = new CyclicBarrier(3); 17 for (int i = 0; i < 3; i++) { 18 Runnable runnable = new Runnable() { 19 public void run() { 20 try { 21 Thread.sleep((long) (Math.random() * 10000)); 22 System.out.println("线程" 23 + Thread.currentThread().getName() 24 + "即将到达集合地点1,当前已有" 25 + (cb.getNumberWaiting() + 1) 26 + "个已经到达," 27 + (cb.getNumberWaiting() == 2 ? "都到齐了,继续走啊" 28 : "正在等候")); 29 cb.await(); 30 31 Thread.sleep((long) (Math.random() * 10000)); 32 System.out.println("线程" 33 + Thread.currentThread().getName() 34 + "即将到达集合地点2,当前已有" 35 + (cb.getNumberWaiting() + 1) 36 + "个已经到达," 37 + (cb.getNumberWaiting() == 2 ? "都到齐了,继续走啊" 38 : "正在等候")); 39 cb.await(); 40 Thread.sleep((long) (Math.random() * 10000)); 41 System.out.println("线程" 42 + Thread.currentThread().getName() 43 + "即将到达集合地点3,当前已有" 44 + (cb.getNumberWaiting() + 1) 45 + "个已经到达," 46 + (cb.getNumberWaiting() == 2 ? "都到齐了,继续走啊" 47 : "正在等候")); 48 cb.await(); 49 } catch (Exception e) { 50 e.printStackTrace(); 51 } 52 } 53 }; 54 service.execute(runnable); 55 } 56 service.shutdown(); 57 } 58 }
标签:
原文地址:http://www.cnblogs.com/litaiqing/p/4650976.html