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应用实例

package com.taoshu.zhifu.workdemo.concurrent;

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

/**
 * Created by yanyg on 2020-05-08.
 */
public class CyclicBarrierTest {
    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        int num = 4;
        CyclicBarrier barrier = new CyclicBarrier(num);
        for (int i = 0; i < num - 1; i++) {
            new Writer(barrier).start();
        }
        // 调用num次
        barrier.await();
        System.out.println("所有线程写入完毕,继续处理其他任务,比如数据操作");

        // 可以再次使用
        for (int i = 0; i < num - 1; i++) {
            new Writer(barrier).start();
        }
        // 调用num次
        barrier.await();
        System.out.println("哈哈哈哈");

    }

    static class Writer extends Thread {
        private CyclicBarrier cyclicBarrier;

        public Writer(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }


        @Override
        public void run() {
            try {
                Thread.sleep(1000); //以睡眠来模拟线程需要预定写入数据操作
                System.out.println("线程" + Thread.currentThread().getName() + "写入数据完毕,等待其他线程写入完毕");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值