CyclicBarrier使用

volatile关键字解析:

http://mp.weixin.qq.com/s?src=3&timestamp=1474600039&ver=1&signature=fA4OwtcYwsEBwff*JKCl2mg-fR9TBZAoKJwxenYeMQ1ltg03UfyoEHJbhNg6pJANiba4TJn8M5knDiJL5m8IhhvE0eZkBtft7f0Y57719vpwqrZQ27FH3STrgvN5ZLzYjZ3pA4gYF*N*jQ5oGuo5wA==

同步辅助类,让N个线程互相等待,子线程结束后,可以启动另一个线程进行汇总  

 * 场景设想:

 *    有一个公司要对3个部门,分别进行工资统计,然后进行对比 ,和汇总

 *    但每个部门的数据还是比较大的, 这时候启动3个线程

 *    当3个线程全部执行结束了,在进行汇总计算总工资数目 

public class CyclicBarrierLatchTest2 {
	
	public static Integer num1;
	public static Integer num2;
	public static Integer num3;
	public static Integer total ;
	public static void main(String[] args) {
		 
		//所有线程执行完毕标识
		final ExecutorService executor = Executors.newFixedThreadPool(3) ; 
		CyclicBarrier bar = new CyclicBarrier(4 , new Runnable() {
			@Override
			public void run() {
				CyclicBarrierLatchTest2.total = CyclicBarrierLatchTest2.num1+ 
						CyclicBarrierLatchTest2.num2+CyclicBarrierLatchTest2.num3 ; 
				System.out.println( "最后计算结果:"+CyclicBarrierLatchTest2.total);
				executor.shutdown();
			}
		}); 
		
		try {
			for(int i=1;i<4;i++){
				Thread.sleep(500);//利用sleep,说明工人开始时间不同
				executor.execute( new SlaveThread3(bar,i));
				//new Thread(new SlaveThread3(bar,i)).start();
			}
			bar.await();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}catch ( Exception e) {
			e.printStackTrace();
		}
		 
		System.out.println("主任务完成。。");
	}
	
}


//工人类
class SlaveThread3  extends Thread{
	 
	private CyclicBarrier  bar  ; 
	private int flag ; 
 
	public SlaveThread3( CyclicBarrier bar ,Integer flag ){
		this.bar = bar ;  
		this.flag= flag ; 
	}
	
	@Override
	public void run() {
		long start = System.currentTimeMillis() ; 
		System.out.println( "线程"+flag+"起止时间"+start);
		
		try {
			takeUp() ;
			//当前工人用力完毕,结束
			bar.await();
		} catch ( Exception e) {
			e.printStackTrace();
		}  
		 
		System.out.println( "线程"+flag+"结束时间"+start);
	}
	
	//抬起
	public void takeUp(){
		 if(flag==1){ //线程1数据统计
			 CyclicBarrierLatchTest2.num1 = 1 ;
		 }else if(flag==2){//线程2数据统计
			 CyclicBarrierLatchTest2.num2 = 1 ;
		 }else if(flag==3){//线程3数据统计
			 CyclicBarrierLatchTest2.num3 = 1 ;
		 }
	}
}

猜你喜欢

转载自username2.iteye.com/blog/2239735
今日推荐