栅栏CyclicBarrier和闭锁CountDownLatch类似,可以说它们都是用来计数,都能阻塞一组线程知道某个事件发生。不同的是闭锁用于等待事件,而栅栏用于等待其他线程。
在前一篇《CountDownLatch——闭锁的实现之一》中提到,在CountDownLatch里有一个计数器,一个线程完成一个任务后调用countdown方法使其计数器-1,等待线程则在执行方法前调用await方法,当CountDownLatch计数器减至0时将会放行的阻塞等待线程。那么CyclicBarrier所谓的等待其他线程是什么意思呢?
我们模拟一个任务线程:
1 package cyclicbarrier; 2 3 import java.util.concurrent.BrokenBarrierException; 4 import java.util.concurrent.CyclicBarrier; 5 6 /** 7 * Created by yulinfeng on 12/19/16. 8 */ 9 public class Task implements Runnable { 10 private final CyclicBarrier cyclicBarrier; 11 12 public Task(CyclicBarrier cyclicBarrier){ 13 this.cyclicBarrier = cyclicBarrier; 14 } 15 16 @Override 17 public void run() { 18 try { 19 System.out.println(Thread.currentThread().getId() + " waiting"); 20 cyclicBarrier.await(); //线程到达时将阻塞,只有当所有线程都到达时,才会打开栅栏 21 System.out.println(Thread.currentThread().getId() + " working"); 22 } catch (InterruptedException e) { 23 e.printStackTrace(); 24 } catch (BrokenBarrierException e) { 25 e.printStackTrace(); 26 } 27 } 28 }
接着我们看看测试代码,使用线程池开启5个线程:
1 package cyclicbarrier; 2 3 import java.util.concurrent.CyclicBarrier; 4 import java.util.concurrent.ExecutorService; 5 import java.util.concurrent.Executors; 6 7 /** 8 * Created by yulinfeng on 12/19/16. 9 */ 10 public class Test { 11 12 public static void main(String[] args){ 13 CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() { 14 //当所有线程到达时执行此线程 15 @Override 16 public void run() { 17 System.out.println("execute barrier"); 18 } 19 }); 20 21 ExecutorService exec = Executors.newCachedThreadPool(); 22 for (int i = 0; i < 5; i++){ 23 exec.execute(new Task(cyclicBarrier)); 24 } 25 } 26 }
执行结果:
时间: 2024-10-09 20:44:19