用ExecutorService&cyclicBarrier&countDownLatch实现...

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

http://my.oschina.net/adwangxiao/blog/110188多线程

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

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

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;.net

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();
	}
}

}code

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

相关文章
相关标签/搜索