Java并发编程

Java多线程之栅栏(CyclicBarrier)

1.基本思路

   a.通过创建CyclicBarrier对象,里面记录了需要等待的线程数。   
	/** The number of parties */
    private final int parties;
    /**
     * 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.
     */
    //还未在栅栏处等待的线程数,当CyclicBarrier刚创建的时候与parties相等,这个值会在dowait方法上做递减。
    private int count;

    /* The command to run when tripped */
    //构造方法传入的Runnable。(可选)
    private final Runnable barrierCommand;
 b.每个需要进入栅栏的线程需要在线程方法中加入await方法,并在此等待放行。
public int await(long timeout, TimeUnit unit)
        throws InterruptedException,
               BrokenBarrierException,
               TimeoutException {
        return dowait(true, unit.toNanos(timeout));
    }
    
public int await() throws InterruptedException, BrokenBarrierException {
        try {
            return dowait(false, 0L);
        } catch (TimeoutException toe) {
            throw new Error(toe); // cannot happen
        }
    }
/**
  例子
**/
public class T implements Runnable {
   
    private final CyclicBarrier barrier;

    public T(CyTclicBarrier barrier) {
        this.barrier = barrier;
    }

    public void run() {
        try {
            System.out.println(name + "进入栅栏等待放行....");
            barrier.await();
            System.out.println(name + "栅栏放行。");
        } catch (InterruptedException e) {
        } catch (BrokenBarrierException e) {
        }
    }
}

2.细节分析

	1.在CyclicBarrier中有一个构造方法需要引起大家的注意。
public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }
这个方法中传入了一个Runnable,根据说明我们知道这个Runnable 会在所有线程(parties)到达栅栏后才会
执行,那么我们有没有想过为什么这个Runnable会在所有线程到达栅栏之后放行之前执行呢。会不会有一部分线程放行之
后这个Runnable 才执行呢?带着这个问题我们分析一下dowait方法。
当我们看到Runnable的时候第一眼看上去肯定是一个线程,没错,但是它却没有开启新线程去执行,而是在同步中执行的
。
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();
        }
    }
栅栏执行流程。

1.thread-1进入dowait方法,首先获取锁。

		final ReentrantLock lock = this.lock;
        lock.lock();

2.count:未进入栅栏的线程数量减一。

int index = --count;
并判断当前是否所有线程都进入栅栏。
if (index == 0) {  // tripped
               ....
}

3.如果还有线程没进入栅栏,则进入循环,通过trip.await()方法,当前线程在此处等待并释放锁(lock)。 如果设置了超时时间则在trip.awaitNanos(nanos)处等待并释放锁。

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();
                }
            }

4.锁释放之后将要进入栅栏的其他线程便又可以获取锁了,获取锁之后又从第1步开始执行到第3步,如此循环往复。 直到最后一个线程进来之后。

最后一个线程进入第2步之后,经过判断所有线程都已经进入栅栏,便开始执行。

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();
                }
            }
首先判断我们是否传入了Runnable如果传入了便会执行
command.run();
**这里需要注意,是直接调用run方法,并不是重新开启线程去执行。**

这里是同步执行而不是异步执行,这就是为什么可以保证传入的Runnable可以在所有线程放行之前优先执行,因为他是

同步执行。

执行完Runnable之后调用
nextGeneration();
private void nextGeneration() {
        // signal completion of last generation
        trip.signalAll();
        // set up next generation
        count = parties;
        generation = new Generation();
    }
trip.signalAll()。唤醒所有在栅栏处等待的线程重新进入锁竞争的状态。
 finally {
            lock.unlock();
        }
这个时候锁已释放。在栅栏处等待的其他线程便会在
 for (;;) {
                try {
                    if (!timed)
                        trip.await();
                    else if (nanos > 0L)
                        nanos = trip.awaitNanos(nanos);

   .......
}
继续执行。

当执行到
if (g != generation)
                    return index;
跳出循环,在finally中释放锁,当前线程执行结束。

如此往复所有线程执行结束。

总结:本文针对CyclicBarrier中的主线路进行了分析。通过AQS的锁进行多线程栅栏的控制。(抛砖引玉,不妥之处还望多多指正)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值