博客
关于我
CyclicBarrier源码探究 (JDK 1.8)
阅读量:408 次
发布时间:2019-03-06

本文共 2967 字,大约阅读时间需要 9 分钟。

CyclicBarrier详解:从实现到使用技巧

1. 相关字段

CyclicBarrier(回环栅栏)通过以下字段实现线程安全:

  • ReentrantLock lock:用于保证线程安全,实现了独占锁机制。
  • Condition trip:线程阻塞时的等待条件。
  • int parties:需要等待的线程数。
  • Runnable barrierCommand:栅栏打开时首先执行的任务。
  • Generation generation:记录当前栅栏所处的代号。
  • int count:当前还需要等待的线程数。

2. 构造函数

CyclicBarrier 提供两个重载构造函数:

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

3. 核心方法

3.1 await方法

  • await():无参数版本,调用dowait(false, 0L)。
  • await(long timeout, TimeUnit unit):带有超时参数,调用dowait(true, unit.toNanos(timeout))。

3.2 dowait方法

dowait 是核心逻辑,实现了栅栏的等待与唤醒机制:

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) {            boolean ranAction = false;            try {                final Runnable command = barrierCommand;                if (command != null)                    command.run();                ranAction = true;                nextGeneration();                return 0;            } finally {                if (!ranAction)                    breakBarrier();            }        }        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 {                    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();    }}

3.2.1 breakBarrier方法

private void breakBarrier() {    generation.broken = true;    count = parties;    trip.signalAll();}

3.2.2 nextGeneration方法

private void nextGeneration() {    trip.signalAll();    count = parties;    generation = new Generation();}

3.2.3 reset方法

public void reset() {    final ReentrantLock lock = this.lock;    lock.lock();    try {        breakBarrier();        nextGeneration();    } finally {        lock.unlock();    }}

4. 问题解析

4.1 dowait中的锁释放问题

在dowait方法中,锁是在finally块中释放的。第一个线程获取锁后进入等待状态,其他线程如何获取锁?答案在于Condition的await方法内部,通过unparkSuccessor唤醒后继线程,允许它们获取锁继续执行。

5. 更新日志

  • 3.19日更新了问题解析的问题1。

转载地址:http://slkkz.baihongyu.com/

你可能感兴趣的文章
Python化身“安全老中医”:一键搞定工控系统漏洞,从零基础到精通,收藏这篇就够了!
查看>>
Python加速运行技巧
查看>>
python办公自动化基础遍历文件夹
查看>>
python办公自动化基础输出文件和文件夹
查看>>
python办公自动化基础搜索文件
查看>>
python知识:@classmethod和@staticmethod的异同
查看>>
python前端之css
查看>>
Python制作进度条,原来有这么多方法
查看>>
Python制作简单的学生成绩管理系统
查看>>
python制作甘特图的基本知识(附Demo)
查看>>
python制作一个简单的服务器,【Python】 做一个简单的 http 服务器
查看>>
Python到底能做什么?它的优点在哪?
查看>>
python利用pytorch库导出图像分割算子
查看>>
python利用pyshark监听网卡来抓包其中pyshark中摸索的一些可用参数
查看>>
python利用excel分析过杀漏失
查看>>
python判断汉字数目
查看>>
python判断文件是空的,如果是空的,就删除
查看>>
python判断密码是否正确_python密码判断是否符合要求的方法
查看>>
python判断字符串包含中文_Python 判断字符串是否包含中文
查看>>
python删除第一行_Python 乱码指北:一行删掉根目录
查看>>