使用java并发工具栅栏(CyclicBarrier)实现多线程等待,同一时刻执行共同任务

  CyclicBarrier,名字就是循环栅栏,栅栏显而易见就是拦住一堆"事情",这里"事情"就是线程,在未达到栅栏指定的线程数时,所有线程都要等待,达到指定数目,共同执行下面的任务。api文档解释:

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

  下面设定一个场景,在运动场上,所有运动员自由走到起跑线,在发令枪发令之前,可以自由热身,但是一旦所有队员已经走到起跑线并准备好,裁判发号施令。程序如下:

  

package com.smikevon.concurrent.tools;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @description: 要求:十个运动员要进行百米赛跑,在赛前运动员各自进行自己的热身运动,然后统一起跑,裁判才开始记时。
 * @date       : 2014年9月17日 下午4:22:15
 */
public class TestCyclicBarrier {

    public static void main(String[] args) throws InterruptedException {

        String[] children = {"小明(1号)","小强(2号)","小海(3号)","小龙(4号)","小武(5号)","小勇(6号)","小鹏(7号)","小飞(8号)","小峰(9号)","小涛(10号)"};

        final Random random = new Random(System.currentTimeMillis());

        final CyclicBarrier barrier = new CyclicBarrier(10,new Runnable() {
            public void run() {
                Thread.currentThread().setName("裁判");
                doing("各就各位,预备,跑");

            }
        });


        //让10个运动员动起来
        for(String child : children){
            new Thread(new Runnable() {
                public void run() {
                    try {
                        doing("我要开始做我的热身运动!");
                        int time = random.nextInt(20000);
                        Thread.sleep(time);
                        doing("我已经做完了热身运动!共耗时"+Long.parseLong(time+"")/1000+"秒!");
                        //等待其他线程执行
                        barrier.await();
                        doing("我已经准备好,当前时间是:"+System.currentTimeMillis());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            },child).start();
        }
    }

    /**
     * @Description:打印出线程的名字
     * @param msg
     * @returType:void
     */
    public static void doing(String msg){
        System.out.println(Thread.currentThread().getName()+":"+msg);
    }

}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。