当前位置:编程学习 > JAVA >>

关于多线程同步的初步教程--Barrier的设计及使用


Barrier是一个多线程编程中经常要用到的同步工具,尤其多用于大数据量的计算过程中的同步。本文以广为流程的Doug Lea的concurrent工具包的Barrier实现为例,进行一点探讨。在Doug Lea的concurrent工具包中,Barrier是一个接口,在concurrent包中提供了两个Barrier的实现:CyclicBarrier和Rendezvous。下面是Barrier接口的定义:

  1. public interface Barrier {
  2.   /** 
  3.    * Return the number of parties that must meet per barrier
  4.    * point. The number of parties is always at least 1.
  5.    **/
  6.   public int parties();
  7.   /**
  8.    * Returns true if the barrier has been compromised
  9.    * by threads leaving the barrier before a synchronization
  10.    * point (normally due to interruption or timeout). 
  11.    * Barrier methods in implementation classes throw
  12.    * throw BrokenBarrierException upon detection of breakage.
  13.    * Implementations may also support some means
  14.    * to clear this status.
  15.    **/
  16.   public boolean broken();
  17. }


    Barrier接口中的方法非常简单,parties()返回所有需要在屏障处同步的线程数;broken()返回一个标志,指示释放是否已被破坏。Barrier接口中并没有提供加入屏障的方法,而是在c和Rendezvous的Barrier实现中提供的。你可以会疑问,为什么不在Barrier接口中提供这些方法呢?因为这些实现的差异迥异,以至于很难在这些实现中提炼出一个共用的方法签名。比如,对于CyclicBarrier加入屏障的方法是:barrier(), 

  1. // CyclicBarrier.java
  2.   public int barrier() throws InterruptedException, BrokenBarrierException {
  3.     return doBarrier(false, 0);
  4.   }
  5.   protected synchronized int doBarrier(boolean timed, long msecs) 
  6.     throws InterruptedException, TimeoutException, BrokenBarrierException  { 
  7.     
  8.     int index = --count_;
  9.     if (broken_) {
  10.       throw new BrokenBarrierException(index);
  11.     }
  12.     else if (Thread.interrupted()) {
  13.       broken_ = true;
  14.       notifyAll();
  15.       throw new InterruptedException();
  16.     }
  17.     else if (index == 0) {  // tripped
  18.       count_ = parties_;
  19.       ++resets_;
  20.       notifyAll();
  21.       try {
  22.         if (barrierCommand_ != null)
  23.           barrierCommand_.run();
  24.         return 0;
  25.       }
  26.       catch (RuntimeException ex) {
  27.         broken_ = true;
  28.         return 0;
  29.       }
  30.     }
  31.     else if (timed && msecs <= 0) {
  32.       broken_ = true;
  33.       notifyAll();
  34.       throw new TimeoutException(msecs);
  35.     }
  36.     else {                   // wait until next reset
  37.       int r = resets_;      
  38.       long startTime = (timed)? System.currentTimeMillis() : 0;
  39.       long waitTime = msecs;
  40.       for (;;) {
  41.         try {
  42. &n
    补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,