栅栏CyclicBarrier和闭锁CountDownLatch类似,可以说它们都是用来计数,都能阻塞一组线程知道某个事件发生。不同的是闭锁用于等待事件,而栅栏用于等待其他线程。

在前一篇《CountDownLatch——闭锁的实现之一》中提到,在CountDownLatch里有一个计数器,一个线程完成一个任务后调用countdown方法使其计数器-1,等待线程则在执行方法前调用await方法,当CountDownLatch计数器减至0时将会放行的阻塞等待线程。那么CyclicBarrier所谓的等待其他线程是什么意思呢?

我们模拟一个任务线程:

 package cyclicbarrier;

 import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier; /**
* Created by yulinfeng on 12/19/16.
*/
public class Task implements Runnable {
private final CyclicBarrier cyclicBarrier; public Task(CyclicBarrier cyclicBarrier){
this.cyclicBarrier = cyclicBarrier;
} @Override
public void run() {
try {
System.out.println(Thread.currentThread().getId() + " waiting");
cyclicBarrier.await(); //线程到达时将阻塞,只有当所有线程都到达时,才会打开栅栏
System.out.println(Thread.currentThread().getId() + " working");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}

接着我们看看测试代码,使用线程池开启5个线程:

 package cyclicbarrier;

 import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* Created by yulinfeng on 12/19/16.
*/
public class Test { public static void main(String[] args){
CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {
//当所有线程到达时执行此线程
@Override
public void run() {
System.out.println("execute barrier");
}
}); ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++){
exec.execute(new Task(cyclicBarrier));
}
}
}

执行结果:

栅栏——CyclicBarrier-LMLPHP

05-11 14:04