栅栏它能阻止一些线程直到某件事情发生或完成。闭锁也可以来同时启动一组线程来执行相关操作,或者等待一组相关操作执行完。但是闭锁是一次性的,一旦进入状态就不能被重置。栅栏(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秒