秒杀多线程之CyclicBarrier

CyclicBarrier是用来一个关卡来阻挡住所有线程,等所有线程全部执行到关卡处时,再统一执行下一步操作。

package com.multithread.cyclicbarrier;



import java.util.concurrent.CyclicBarrier;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;



import com.multithread.main.ExampleInterface;



public class CyclicBarrierExample extends ExampleInterface {



    @Override

    public void startDemo() {

         System.out.println("开始线程:"+Thread.currentThread().getId());

        // TODO Auto-generated method stub

        final CyclicBarrier barrier = new CyclicBarrier(3, new Runnable() {



            /*

             * 运行在最后一个await到达的线程,不是主线程!

             * */

            @Override

            public void run() {

                System.out.println("所有选手ready"+"线程:"+Thread.currentThread().getId());

            }

        });

        

        ExecutorService executor = Executors.newFixedThreadPool(3); 

        executor.submit(new Thread(new Runner(barrier, "1号选手")));  

        executor.submit(new Thread(new Runner(barrier, "2号选手")));  

        executor.submit(new Thread(new Runner(barrier, "3号选手")));  

  

        executor.shutdown();

    }



}



package com.multithread.cyclicbarrier;



import java.util.Random;

import java.util.concurrent.BrokenBarrierException;

import java.util.concurrent.CyclicBarrier;



public class Runner implements Runnable {



     // 一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)  

    private CyclicBarrier barrier;  

  

    private String name;  

  

    public Runner(CyclicBarrier barrier, String name) {  

        super();  

        this.barrier = barrier;  

        this.name = name;  

    }  

  

    @Override  

    public void run() {  

        try {  

            Thread.sleep(1000 * (new Random()).nextInt(8));  

            System.out.println(name + " 准备好了..."+"线程:"+Thread.currentThread().getId());  

            // barrier的await方法,在所有参与者都已经在此 barrier 上调用 await 方法之前,将一直等待。  

            barrier.await();  

        } catch (InterruptedException e) {  

            e.printStackTrace();  

        } catch (BrokenBarrierException e) {  

            e.printStackTrace();  

        }  

        System.out.println(name + " 起跑!"+"线程:"+Thread.currentThread().getId());  

    }  

}

运行结果:

开始线程:1
3号选手 准备好了...线程:14
1号选手 准备好了...线程:10
2号选手 准备好了...线程:12
所有选手ready线程:12
2号选手 起跑!线程:12
3号选手 起跑!线程:14
1号选手 起跑!线程:10

 

你可能感兴趣的:(Cyclicbarrier)