1. 程式人生 > >柵欄CyclicBarrier

柵欄CyclicBarrier

    @Test
    public void test03() throws Exception{
        CyclicBarrier cb = new CyclicBarrier(2);  //new柵欄,並作為構造方法傳入
        new Thread(new Horse1(cb)).start();
        new Thread(new Horse2(cb)).start();
        Thread.sleep(2000);  //防止主執行緒提前結束掉
    }
class Horse1 implements Runnable{

    CyclicBarrier cb;
    public Horse1(CyclicBarrier cb) {
        this.cb = cb;
    }

    @Override
    public void run() {
        try {
            System.out.println("horse1 arrive the barrier");
            cb.await();  //等待-1
            System.out.println("horse1 running");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
class Horse2 implements Runnable{
    CyclicBarrier cb;
    public Horse2(CyclicBarrier cb) {
        this.cb = cb;
    }

    @Override
    public void run() {

        System.out.println("horse2 not ready");
        try {
            Thread.sleep(1000);
            System.out.println("horse2 arrive the barrier");
            cb.await();   //等待-1   等等待的數量滿2之後,放行
            System.out.println("horse2 running");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
horse1 arrive the barrier
horse2 not ready
horse2 arrive the barrier
horse2 running
horse1 running