多线程 -同时让10个线程执行一项工作。

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

/**
 * 要求实现10个线程同时执行,并通知比赛结束
 * 使用到的类有:
 * 	1:CountDownLatch,如其所写,是一个倒计数的锁存器,当计数减至0时触发特定的事件
 * 		1.1	countDown方法,计数器减1
 * 		1.2	await方法,阻塞当前线程,直到计数器为0
 * 		1.3 await(long timeout, TimeUnit unit),等待指定时长后立刻开始执行任务
 *  2:ExecutorService,线程池
 *  
 *  实现方式:
 *  	1:使用两个同步所,一个用来通知比赛开始,一个用来通知比赛结束。获取比赛结束才可以开始后续工作。
 * 
 * @author admin
 *
 */
public class SameTimeMoreThreads {
	
	public static final int threadCount = 10;
	
	public static void main(String[] args) {
		
		/**
		 * 线程池
		 */ 
		ExecutorService exe = Executors.newFixedThreadPool(threadCount);
		/**
		 * 口令枪
		 * 当口令枪起,比赛开始
		 */
		 final CountDownLatch matchGun = new CountDownLatch(1);
		 
		 /**
		  * 比赛者完成比赛用来通知的枪
		  */
		 final CountDownLatch endGun = new CountDownLatch(threadCount);
		 
		 for(int i=0;i<threadCount;i++){
			 Worker worker = new Worker(i+1,matchGun,endGun);
			 exe.execute(worker);            //分配线程
		 }
		 /**
		  * 比赛枪响起
		  */
		 matchGun.countDown();
         try{
        	 /**
        	  * 等待,直到最后一个队员完成比赛。
        	  */
        	 endGun.await();           
         }catch (InterruptedException e) {
             e.printStackTrace();
         }finally{
             System.out.println("比赛结束!");
         }
         /**
          * 关闭线程池。
          */
         exe.shutdown();
		 
	}
	/**
	 * 内部类,具体执行者
	 *
	 */
	static class Worker implements Runnable {
		/**
		 * 比赛队员牌号
		 */
		private int id;
		/**
		 * 比赛抢
		 */
	     private CountDownLatch begin;
	     /**
	      * 完成比赛通知枪
	      */
	    private CountDownLatch end;
		 
	    public Worker(int i, CountDownLatch begin, CountDownLatch end) {
	         super();
	         this.id = i;
	         this.begin = begin;
	         this.end = end;
	     }
	    
		public void run() {
			 try{
				 /**
				  * 等待比赛枪响起
				  */
	             begin.await(); 
	             /**
	              * 如果枪响,则开始进入比赛
	              */
	             Thread.sleep((long)(Math.random()*100));    //随机分配时间,即运动员完成时间
	             System.out.println("队员["+id+"]完成比赛.");
	         }catch (InterruptedException e) {
	             e.printStackTrace();
	         }finally{
	        	 /**
	        	  * 通知仲裁,完成该队员完成比赛
	        	  */
	             end.countDown();    //使end状态减1,最终减至0
	         }
			
		} 
		
	}
}

猜你喜欢

转载自01jiangwei01.iteye.com/blog/2230545