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?"都到齊了,繼續走啊":"正在等候"));cb.await();Thread.sleep((long)(Math.random()*10000));System.out.println("線程" + Thread.currentThread().getName() + "即將到達集合地點2,當前已有" + (cb.getNumberWaiting()+1) + "個已經到達," + (cb.getNumberWaiting()==2?"都到齊了,繼續走啊":"正在等候"));cb.await();Thread.sleep((long)(Math.random()*10000));System.out.println("線程" + Thread.currentThread().getName() + "即將到達集合地點3,當前已有" + (cb.getNumberWaiting() + 1) + "個已經到達," + (cb.getNumberWaiting()==2?"都到齊了,繼續走啊":"正在等候"));cb.await();} catch (Exception e) {e.printStackTrace();}}};service.execute(runnable);}service.shutdown();}}
運行結果如下:
線程pool-1-thread-3即將到達集合地點1,當前已有1個已經到達,正在等候
線程pool-1-thread-1即將到達集合地點1,當前已有2個已經到達,正在等候
線程pool-1-thread-2即將到達集合地點1,當前已有3個已經到達,都到齊了,繼續走啊
線程pool-1-thread-3即將到達集合地點2,當前已有1個已經到達,正在等候
線程pool-1-thread-1即將到達集合地點2,當前已有2個已經到達,正在等候
線程pool-1-thread-2即將到達集合地點2,當前已有3個已經到達,都到齊了,繼續走啊
線程pool-1-thread-1即將到達集合地點3,當前已有1個已經到達,正在等候
線程pool-1-thread-3即將到達集合地點3,當前已有2個已經到達,正在等候
線程pool-1-thread-2即將到達集合地點3,當前已有3個已經到達,都到齊了,繼續走啊
整理自教程