用ExecutorService&cyclicBarrier&countDownLatch实现...

三世轮回 提交于 2019-12-06 15:35:43

这个博客介绍的不错:http://my.oschina.net/jielucky/blog/157946

http://my.oschina.net/adwangxiao/blog/110188

我再顺着这个博客往下写:

赛马是个不错的多线程场景,包括所有赛马都准备好,然后指挥官喊预备跑部分,然后所有赛马跑到了,关闭所有跑道两部分,这个场景可以很好的运用多线程。如下图所示. 在此输入图片描述 package com.xue.gang.barrier;

import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;

public class CyclicBarrierMutiRunner {

public static void main(String args[]) throws InterruptedException{
	
	final int  size = 10;
	
	ExecutorService executorService = Executors.newCachedThreadPool();
	/**用户指挥官部分*/
	CyclicBarrier cyclicBarrier = new CyclicBarrier(size,new Commander());
	
	/**用户关闭线程池*/
	CountDownLatch countDownLatch = new CountDownLatch(size);
	for(int i =1;i<=size;i++){
		executorService.execute(new Horse(cyclicBarrier,countDownLatch,i+"——号"));
	}
	
	countDownLatch.await();
	executorService.shutdown();
}


/**指挥官*/
static class Commander implements Runnable{
	
	public Commander() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void run() {
		
		System.out.println("---------->预备...开始..跑...!!!!!!!!!!!!!!!!!!!!!!!!");
		
	}
}
/**马* */
static class Horse implements Runnable{
	
	/**用于指挥官**/
	private CyclicBarrier cyclicBarrier;
	
	/**用于线程池子*/
	private CountDownLatch countDownLatch;
	
	private String horseName;
	
	

	public Horse(CyclicBarrier cyclicBarrier,
			CountDownLatch countDownLatch, String horseName) {
		super();
		this.cyclicBarrier = cyclicBarrier;
		this.countDownLatch = countDownLatch;
		this.horseName = horseName;
	}



	public void run() {
		
		System.out.println("报告,"+this.horseName+":在去赛场的路上...");
		try {
			//等待一个随机数
			Thread.sleep((long)Math.random()*10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("报告,"+this.horseName+":准备好了,等待其它马准备好了,一起跑...");
		try {
			//通知其它线程,准备好了
			this.cyclicBarrier.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			e.printStackTrace();
		}
		System.out.println("报告,"+this.horseName+":飞奔中...");
		//报告跑到了..
		this.countDownLatch.countDown();
	}
}

}

参考:http://my.oschina.net/jielucky/blog/157946

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!