CyclicBarrier源码解析

概述

  • 简介

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.

  CyclicBarrier是一个同步工具类,它允许一组线程互相等待,直到到达某个栅栏点(common barrier point)。与CountDownLatch不同的是该barrier在释放等待线程后可以重用,所以称它为循环(Cyclic)的屏障(Barrier)。

CyclicBarrier字面理解是循环的栅栏,之所以称之为循环的是因为在等待线程释放后,该栅栏还可以复用。

  CyclicBarrier支持一个可选的Runnable命令,在一组线程中的最后一个线程到达之后(但在释放所有线程之前),该命令只在每个屏障点运行一次。若在继续所有参与线程之前更新共享状态,此屏障操作很有用。

  • 使用场景

需要所有的子任务都完成时,才执行主任务,这个时候就可以选择使用CyclicBarrier

源码解析

成员变量

/** The lock for guarding barrier entry */
private final ReentrantLock lock = new ReentrantLock();
/** Condition to wait on until tripped */
private final Condition trip = lock.newCondition();
/** The number of parties */
private final int parties; //拦截的线程数量
/* The command to run when tripped */
private final Runnable barrierCommand; //当屏障撤销时,需要执行的屏障操作
/** The current generation */
//当前的Generation。每当屏障失效或者开闸之后都会自动替换掉。从而实现重置的功能。
private Generation generation = new Generation();

/**
* Number of parties still waiting. Counts down from parties to 0
* on each generation.  It is reset to parties on each new
* generation or when broken.
*/
//还能阻塞的线程数(即parties-当前阻塞的线程数),当新建generation或generation被破坏时,count会被重置。因为对Count的操作都是在获取锁之后,所以不需要其他同步措施
private int count;

构造方法

    public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }

    public CyclicBarrier(int parties) {
        this(parties, null);
    }

成员方法


/**
* Updates state on barrier trip and wakes up everyone.
* Called only while holding lock.
*/
private void nextGeneration() {
   // signal completion of last generation
   trip.signalAll();
   // set up next generation
   count = parties;
   generation = new Generation();
}


/**
* Sets current barrier generation as broken and wakes up everyone.
* Called only while holding lock.
*/
private void breakBarrier() {
   generation.broken = true;
   count = parties;
   trip.signalAll();
}

/**
* Returns the number of parties required to trip this barrier.
*/
public int getParties() {
   return parties;
}

/**
* Waits until all {@linkplain #getParties parties} have invoked
* {@code await} on this barrier.
*/
public int await() throws InterruptedException, BrokenBarrierException {
   try {
       return dowait(false, 0L);
   } catch (TimeoutException toe) {
       throw new Error(toe); // cannot happen
   }
}

/**
* Waits until all {@linkplain #getParties parties} have invoked
* {@code await} on this barrier, or the specified waiting time elapses.
*/
public int await(long timeout, TimeUnit unit)
   throws InterruptedException,
          BrokenBarrierException,
          TimeoutException {
   return dowait(true, unit.toNanos(timeout));
}

/**
* Main barrier code, covering the various policies.
*/
private int dowait(boolean timed, long nanos)
   throws InterruptedException, BrokenBarrierException,
          TimeoutException {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
       final Generation g = generation;

       if (g.broken)
           throw new BrokenBarrierException();

       if (Thread.interrupted()) {
           breakBarrier();
           throw new InterruptedException();
       }

       int index = --count;
       if (index == 0) {  // tripped
           boolean ranAction = false;
           try {
               final Runnable command = barrierCommand;
               if (command != null)
                   command.run();
               ranAction = true;
               nextGeneration();
               return 0;
           } finally {
               if (!ranAction)
                   breakBarrier();
           }
       }

       // loop until tripped, broken, interrupted, or timed out
       for (;;) {
           try {
               if (!timed)
                   trip.await();
               else if (nanos > 0L)
                   nanos = trip.awaitNanos(nanos);
           } catch (InterruptedException ie) {
               if (g == generation && ! g.broken) {
                   breakBarrier();
                   throw ie;
               } else {
                   // We're about to finish waiting even if we had not
                   // been interrupted, so this interrupt is deemed to
                   // "belong" to subsequent execution.
                   Thread.currentThread().interrupt();
               }
           }

           if (g.broken)
               throw new BrokenBarrierException();

           if (g != generation)
               return index;

           if (timed && nanos <= 0L) {
               breakBarrier();
               throw new TimeoutException();
           }
       }
   } finally {
       lock.unlock();
   }
}


/**
* Queries if this barrier is in a broken state.
*/
public boolean isBroken() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
       return generation.broken;
   } finally {
       lock.unlock();
   }
}

/**
* Resets the barrier to its initial state.
*/
public void reset() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
       breakBarrier();   // break the current generation
       nextGeneration(); // start a new generation
   } finally {
       lock.unlock();
   }
}

/**
* Returns the number of parties currently waiting at the barrier.
*/
public int getNumberWaiting() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
       return parties - count;
   } finally {
       lock.unlock();
   }
}

内部类

/**
* Each use of the barrier is represented as a generation instance.
*/
private static class Generation {
   boolean broken = false;
}

循环栅栏CyclicBarrier应用实例

源码

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

//先执行Soldier的run方法,再执行BarrierRun的run方法
public class CyclicBarrierTest {

    public static class Soldier implements Runnable {

        private String soldierName;
        private final CyclicBarrier cyclic;

        public Soldier(CyclicBarrier cyclic, String soldierName) {
            this.soldierName = soldierName;
            this.cyclic = cyclic;
        }

        @Override
        public void run() {
            try {
                // 栅栏点一,针对doTask方法
                // 等待所有士兵到齐
                cyclic.await();
                doWork();
                // 栅栏点二,针对doWork方法
                // 等待所有士兵完成工作
                cyclic.await();
            } catch (InterruptedException e) {// 在等待过程中,线程被中断
                e.printStackTrace();
            } catch (BrokenBarrierException e) {// 表示当前CyclicBarrier已经损坏.系统无法等到所有线程到齐了.
                e.printStackTrace();
            }
        }

        void doWork() {
            try {
                Thread.sleep(Math.abs(new Random().nextInt() % 10000));
                System.out.println(soldierName + ":任务完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static class BarrierRun implements Runnable {
        boolean flag;
        int num;

        public BarrierRun(boolean flag, int num) {
            this.flag = flag;
            this.num = num;
        }

        @Override
        public void run() {
            if (flag) {
                System.out.println("司令:[士兵" + num + "个,任务完成!]");
            } else {
                System.out.println("司令:[士兵" + num + "个,集合完毕!]");
                flag = true;
            }
        }
    }

    public static void doTask(int i)    {
        System.out.println("士兵" + i + "报道! ");
    }

    public static void main(String[] args) {
        final int soldierNum = 10;
        Thread[] allSoldier = new Thread[soldierNum];
        boolean flag = false;
        CyclicBarrier cyclic = new CyclicBarrier(soldierNum, new BarrierRun(flag, soldierNum));


        System.out.println("吹响号角,集合队伍! ");
        for (int i = 0; i < soldierNum; i++) {
            doTask(i);
            allSoldier[i] = new Thread(new Soldier(cyclic, "士兵" + i));
            allSoldier[i].start();
        }
    }
}

运行结果

这里写图片描述

猜你喜欢

转载自blog.csdn.net/thebigdipperbdx/article/details/80727060