栅栏原理 java,线程屏障CyclicBarrier实现原理

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, longnanos)

throws InterruptedException, BrokenBarrierException,

TimeoutException {

final ReentrantLocklock = this.lock;lock.lock(); // 1try{

final Generation g=generation;if(g.broken)throw newBrokenBarrierException();if(Thread.interrupted()) {

breakBarrier();throw newInterruptedException();

}int index = --count; // 2if (index == 0) { // 3

boolean ranAction = false;try{

final Runnable command=barrierCommand;if (command != null)

command.run();

ranAction= true;

nextGeneration(); // 4return 0;

}finally{if (!ranAction)

breakBarrier(); // 5

}

}//loop until tripped, broken, interrupted, or timed out

for(;;) {try{if (!timed)

trip.await(); // 6else if (nanos > 0L)

nanos=trip.awaitNanos(nanos);

}catch(InterruptedException ie) {if (g == generation && !g.broken) {

breakBarrier();throwie;

}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 newBrokenBarrierException();if (g !=generation)returnindex;if (timed && nanos <= 0L) {

breakBarrier();throw newTimeoutException();

}

}

}finally{lock.unlock(); // 7

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值