JAVA并发工具—CyclicBarrier

今天来介绍一下并发库中的另一个工具——障碍物(CyclicBarrier)

/**
 *  基于ReentrantLock实现,常用方法如下:
 *  1. CyclicBarrier(3): 设置计数
 *  2. await(): 计数减一
 *  	2.1 如果计数大于0,释放当前线程持有的锁,唤醒下一个等待线程(如果没有执行过2.2,此处应该没有线程可被唤醒),挂起当前线程(condition.await())
 *  	2.2 如果计数等于0,唤醒下一个线程(2.1中等待的线程),继续执行到下一个集结点(重新开始计数)
 *  
 */
public class CyclicBarrierTest {
	
	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		final CyclicBarrier cb = new CyclicBarrier(3);
		for (int i = 0; i < 3; i++) {
		    service.execute(() -> {
			try {
			    Thread.sleep((long) (Math.random() * 10000));
			    System.out.println("thread: " + Thread.currentThread().getName() + "到达集合点1,已有" + (cb.getNumberWaiting()+1) + "人到达");
			    cb.await();
			    Thread.sleep((long) (Math.random() * 10000));
			    System.out.println("thread: " + Thread.currentThread().getName() + "到达集合点2,已有" + (cb.getNumberWaiting()+1) + "人到达");
			    cb.await();
			    Thread.sleep((long) (Math.random() * 10000));
			    System.out.println("thread: " + Thread.currentThread().getName() + "到达集合点3,已有" + (cb.getNumberWaiting()+1) + "人到达");
		            cb.await();
		        } catch (Exception e) {
			    e.printStackTrace();
			}
		    });
		}
		service.shutdown();
	}
}

await

public int await() throws InterruptedException, BrokenBarrierException {
    try {
        return dowait(false, 0L);
    } catch (TimeoutException toe) {
        throw new Error(toe); // cannot happen
    }
}

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

private void nextGeneration() {
    // signal completion of last generation
    trip.signalAll();
    // set up next generation
    count = parties;
    generation = new Generation();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值