闭锁CountDownLatch与栅栏CyclicBarrier

来源:互联网 发布:楚乔传网络播放量 编辑:程序博客网 时间:2024/04/28 11:26

原文地址:http://blog.csdn.net/lmc_wy/article/details/7866863


最近在看java并发相关的书籍,有一些同步的知识是平常不常用但是觉得会很有用的东西,这里参考别人的文章和自己的理解,将闭锁和栅栏的用途与区别简单描述一下。


闭锁:一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。即,一组线程等待某一事件发生,事件没有发生前,所有线程将阻塞等待;而事件发生后,所有线程将开始执行;闭锁最初处于封闭状态,当事件发生后闭锁将被打开,一旦打开,闭锁将永远处于打开状态。

    闭锁CountDownLatch唯一的构造方法CountDownLatch(int count),当在闭锁上调用countDown()方法时,闭锁的计数器将减1,当闭锁计数器为0时,闭锁将打开,所有线程将通过闭锁开始执行。


栅栏:一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点。利用栅栏,可以使线程相互等待,直到所有线程都到达某一点,然后栅栏将打开,所有线程将通过栅栏继续执行。CyclicBarrier支持一个可选的Runnable 参数,当线程通过栅栏时,runnable对象将被调用。构造函数CyclicBarrier(int parties,Runnable barrierAction),当线程在CyclicBarrier对象上调用await()方法时,栅栏的计数器将增加1,当计数器为parties时,栅栏将打开。


区别:闭锁用于所有线程等待一个外部事件的发生;栅栏则是所有线程相互等待,直到所有线程都到达某一点时才打开栅栏,然后线程可以继续执行。


示例:引用自http://aaron-han.iteye.com/blog/1591755

1. 有五个人,一个裁判。这五个人同时跑,裁判开始计时,五个人都到终点了,裁判喊停,然后统计这五个人从开始跑到最后一个撞线用了多长时间。

[java] view plaincopy
  1. import java.util.concurrent.CountDownLatch;    
  2.     
  3. public class Race {    
  4.     
  5.     public static void main(String[] args) {    
  6.         final int num = 5;    
  7.         final CountDownLatch begin = new CountDownLatch(1);    
  8.         final CountDownLatch end = new CountDownLatch(num);    
  9.     
  10.         for (int i = 0; i < num; i++) {    
  11.             new Thread(new AWorker(i, begin, end)).start();    
  12.         }    
  13.     
  14.         // judge prepare...    
  15.         try {    
  16.             Thread.sleep((long) (Math.random() * 5000));    
  17.         } catch (InterruptedException e1) {    
  18.             e1.printStackTrace();    
  19.         }    
  20.     
  21.         System.out.println("judge say : run !");    
  22.         begin.countDown();    
  23.         long startTime = System.currentTimeMillis();    
  24.     
  25.         try {    
  26.             end.await();    
  27.         } catch (InterruptedException e) {    
  28.             e.printStackTrace();    
  29.         } finally {    
  30.             long endTime = System.currentTimeMillis();    
  31.             System.out.println("judge say : all arrived !");    
  32.             System.out.println("spend time: " + (endTime - startTime));    
  33.         }    
  34.     
  35.     }    
  36.     
  37. }    
  38.     
  39. class AWorker implements Runnable {    
  40.     final CountDownLatch begin;    
  41.     final CountDownLatch end;    
  42.     final int id;    
  43.     
  44.     public AWorker(final int id, final CountDownLatch begin,    
  45.             final CountDownLatch end) {    
  46.         this.id = id;    
  47.         this.begin = begin;    
  48.         this.end = end;    
  49.     }    
  50.     
  51.     @Override    
  52.     public void run() {    
  53.         try {    
  54.             System.out.println(this.id + " ready !");    
  55.             begin.await();    
  56.             // run...    
  57.             Thread.sleep((long) (Math.random() * 10000));    
  58.         } catch (Throwable e) {    
  59.             e.printStackTrace();    
  60.         } finally {    
  61.             System.out.println(this.id + " arrived !");    
  62.             end.countDown();    
  63.         }    
  64.     }    
  65.     
  66. }    

2. 继续,还是这五个人(这五个人真无聊..),这次没裁判。规定五个人只要都跑到终点了,大家可以喝啤酒。但是,只要有一个人没到终点,就不能喝。 这里也没有要求大家要同时起跑(当然也可以,加latch)。
[java] view plaincopy
  1. import java.util.concurrent.BrokenBarrierException;  
  2. import java.util.concurrent.CyclicBarrier;  
  3.   
  4. public class Beer {  
  5.   
  6.     public static void main(String[] args) {  
  7.         final int count = 5;  
  8.         final CyclicBarrier barrier = new CyclicBarrier(count, new Runnable() {  
  9.             @Override  
  10.             public void run() {  
  11.                 System.out.println("drink beer!");  
  12.             }  
  13.         });  
  14.   
  15.         // they do not have to start at the same time...  
  16.         for (int i = 0; i < count; i++) {  
  17.             new Thread(new Worker(i, barrier)).start();  
  18.         }  
  19.     }  
  20.   
  21. }  
  22.   
  23. class Worker implements Runnable {  
  24.     final int id;  
  25.     final CyclicBarrier barrier;  
  26.   
  27.     public Worker(final int id, final CyclicBarrier barrier) {  
  28.         this.id = id;  
  29.         this.barrier = barrier;  
  30.     }  
  31.   
  32.     @Override  
  33.     public void run() {  
  34.         try {  
  35.             System.out.println(this.id + "starts to run !");  
  36.             Thread.sleep((long) (Math.random() * 10000));  
  37.             System.out.println(this.id + "arrived !");  
  38.             this.barrier.await();  
  39.         } catch (InterruptedException e) {  
  40.             e.printStackTrace();  
  41.         } catch (BrokenBarrierException e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.     }  


0 0