CyclieBarrier::dowait 代码笔记

private final ReentrantLock lock = new ReentrantLock();

private static class Generation {
    Generation() {}                  
    boolean broken;                 
}
private Generation generation = new Generation();

// CyclieBarrier::dowait
// 是CyclieBarrier定时和非定时版本的wait()函数的母函数
// 根据参数不同可实现定时或非定时版本的wait
private int dowait(boolean timed, long nanos)
    throws InterruptedException, BrokenBarrierException,
            TimeoutException {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        final Generation g = generation;
        // Generation对象被破坏,此时不能执行等待操作
        if (g.broken)
            throw new BrokenBarrierException();

        // 当前线程已经被中断,破坏当前的Generation并抛出异常
        if (Thread.interrupted()) {
            breakBarrier();
            throw new InterruptedException();
        }

        int index = --count;
        // index==0 说明当前等待线程数达到阈值,触发CyclieBarrier
        if (index == 0) {  // tripped
            // 如果当前CyclieBarrier设置了触发时的操作,则使用当前线程执行此操作
            Runnable command = barrierCommand;
            if (command != null) {
                try {
                    command.run();
                } catch (Throwable ex) {
                    breakBarrier();
                    throw ex;
                }
            }
            // 开启一个新的Generation,释放目前等待的所有线程,重置等待线程数量阈值
            nextGeneration();
            return 0;
        }

        // loop until tripped, broken, interrupted, or timed out
        for (;;) {
            try {
                if (!timed)
                    trip.await();
                else if (nanos > 0L)
                    nanos = trip.awaitNanos(nanos); // 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();
    }
}

 

posted @ 2021-05-28 10:52  榆木脑袋0v0  阅读(119)  评论(0)    收藏  举报