线程同步工具类之栅栏

栅栏它能阻止一些线程直到某件事情发生或完成。闭锁也可以来同时启动一组线程来执行相关操作,或者等待一组相关操作执行完。但是闭锁是一次性的,一旦进入状态就不能被重置。栅栏(Barrier)类似于闭锁,闭锁用于等待事件,而栅栏用于等待其它线程,栅栏与闭锁的区别在于,所有线程必须同时到达栅栏的位置,才能继续执行。

下面是一个例子,例如进行一个比较大的耗时计算,将其分割成8个公式,计算时间分别为1,2,3,4,5,6,7,8秒,同时计算的耗时是8秒,顺序执行的时间是36秒,性能提升明显。

下面程序代码

public class ParallelCompute {
	private final CyclicBarrier barrier;
	//闭锁用来同时开启一组线程执行计算操作来计算耗时
	private final CountDownLatch startGate=new CountDownLatch(1);
	private final Computer[] computers;
	
	public ParallelCompute() {
		final long startTime=System.currentTimeMillis();
		int count=Runtime.getRuntime().availableProcessors();
		this.barrier=new CyclicBarrier(count, new Runnable() {
			
			@Override
			public void run() {
				long time=System.currentTimeMillis()-startTime;
				System.out.println("计算公式共耗时"+time+"毫秒");
			}
		});
		this.computers=new Computer[count];
		for (int i = 0; i < count; i++) {
			computers[i]=new Computer(i+1,startGate);
			Thread thread=new Thread(computers[i]);
			thread.start();
		}
	}

	private class Computer implements Runnable{
		private int time;
		private CountDownLatch startGate;
		public Computer(int time,CountDownLatch startGate) {
			super();
			this.time = time;
			this.startGate=startGate;
		}

		@Override
		public void run() {
			try {
				startGate.await();
				System.out.println("公式"+time+"正在计算,将消耗时间"+time+"秒");
				Thread.sleep(time*1000);
				barrier.await();
				// 等待其他线程完成后,然后继续执行做其他事情
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	protected void startCompute(){
		startGate.countDown();
	}
}

public static void main(String[] args) {
		ParallelCompute parallelCompute=new ParallelCompute();
		parallelCompute.startCompute();
		
	}

运行结果可以看出,最终8个公式执行时间共耗时8秒

212615_3xtQ_255939.png

转载于:https://my.oschina.net/u/255939/blog/530163

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值