用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

相關文章
相關標籤/搜索