同步工具类之CyclicBarrier

2017-01-10  本文已影响53人  evil_ice
一, CyclicBarrier栅栏简介
二, CyclicBarrier示例
public class Test {
    private static final int N = 10;

    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier barrier = new CyclicBarrier(N, new Runnable() {

            @Override
            public void run() {
                        //所有线程都到达才会执行,且由最后一个到达的线程执行
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "   所有的任务都已经到达栅栏位置,栅栏打开了   "+System.currentTimeMillis() );
            }

        });
        test(barrier,N);
        test(barrier,N);
    }
    
    private static void test(CyclicBarrier barrier,int nThread) throws InterruptedException{
        for(int i=0; i< nThread-1; i++){
            CyclicBarrierThread t = new CyclicBarrierThread(barrier);
            t.start();
        }
        
        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName() + "   所有子任务执行完毕  "+System.currentTimeMillis());
        System.out.println("******************************************");
              //重置以便于复用
        barrier.reset();
    }
}

class CyclicBarrierThread extends Thread {
    CyclicBarrier barrier;

    CyclicBarrierThread(CyclicBarrier barrier) {
        this.barrier = barrier;
    }

    @Override
    public void run() {
        try {
            barrier.await();
            System.out.println(Thread.currentThread().getName() + "   执行了 "+System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}

参考:
<<java编发编程实战>>

上一篇下一篇

猜你喜欢

热点阅读