CyclicBarrier 简单的demo,思考应用场景

CyclicBarrier:是循环屏障,所有的线程必须全部做完事情之后,线程之间相互等待,才会向下执行,同事也可重复利用。


public class TestClass {

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(10, new Runnable() {
            @Override
            public void run() {
                System.out.println("全部干完了,可以以自由活动了");
            }
        });
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
//-----------已经超过10次,在自行将重复利用CyclicBarrier -----------------
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();
        new Thread(new Work(barrier)).start();


    }
}

class Work implements Runnable {
    private CyclicBarrier barrier;

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

    @Override
    public void run() {

        try {
            System.out.println(Thread.currentThread().getName()+"--正在干活--");
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName()+"--干完了,等待其work的干完--");
            barrier.await();
            System.out.println(Thread.currentThread().getName()+"--开始自由活动--");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}


你可能感兴趣的:(java,多线程)