本文主要是介绍简单了解CyclicBarrier,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
什么是CyclicBarrier?
CyclicBarrier是Java的一个同步类,用于协作多线程,同时也是一个共享锁
CyclicBarrier的使用场景
多线程一起开始
异步线程之间互相等待
public static void main(String[] args) throws IOException {CyclicBarrier cyclicBarrier = new CyclicBarrier(3);for (int i = 0; i < 6; i++) {new MyThread(cyclicBarrier).start();}System.in.read();
}static class MyThread extends Thread {CyclicBarrier cyclicBarrier;public MyThread(CyclicBarrier cyclicBarrier) {this.cyclicBarrier = cyclicBarrier;}@Overridepublic void run() {try {// 获取到锁Thread.sleep(1000 + new Random().nextInt(3000));System.out.println(Thread.currentThread().getName() + "start");cyclicBarrier.await();} catch (Exception e) {throw new RuntimeException(e);}System.out.println(Thread.currentThread().getName() + "end");}
}
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;
}
成员变量
// 每次计数都是一个新的Generation
private static class Generation {boolean broken = false;
}private final ReentrantLock lock = new ReentrantLock();private final Condition trip = lock.newCondition();// 到达屏障需要的总线程数
private final int parties;// 线程数到达屏障的时候执行的方法
private final Runnable barrierCommand;// 当前的Generation
private Generation generation = new Generation();// 到达屏障还差多少线程数
private int count;
await()
public int await() throws InterruptedException, BrokenBarrierException {try {return dowait(false, 0L);} catch (TimeoutException toe) {throw new Error(toe); // cannot happen}
}
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) { // trippedboolean ranAction = false;try {final Runnable command = barrierCommand;// 执行方法if (command != null)command.run();ranAction = true;// 唤醒条件队列所有线程,并且更新屏障nextGeneration();return 0;} finally {// 将当前屏障生成设置为已损坏并唤醒条件队列所有线程if (!ranAction)breakBarrier();}}// 循环直到当前线程数到达屏障、线程被中断、超时for (;;) {try {// timed 表示是否采用超时机制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();}
}
nextGeneration():开启下一轮循环,重置count,唤醒条件队列所有的线程
private void nextGeneration() {// signal completion of last generationtrip.signalAll();// set up next generationcount = parties;generation = new Generation();
}
breakBarrier():设置当前循环为被打断状态,重置count,唤醒条件队列所有的线程
private void breakBarrier() {generation.broken = true;count = parties;trip.signalAll();
}
这篇关于简单了解CyclicBarrier的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!