文章目录
简介用法类属性await()总结
简介
CyclicBarrier可以阻塞一组线程直到这些线程同时达到某个条件才继续执行。 当线程到达栅栏位置时将调用await方法,这个方法将阻塞当前线程直到所有线程都到达栅栏位置。如果所有线程都到达栅栏位置,那么栅栏将打开,此时所有的线程都将被释放,而栅栏将被被重置以便下次使用。
用法
public static void main(String
[] args
) {
CyclicBarrier c
= new CyclicBarrier(5);
for (int i
= 0; i
< 5; i
++) {
new Thread(()->{
try {
System
.out
.println(Thread
.currentThread().getName() + "...inti");
c
.await();
System
.out
.println(Thread
.currentThread().getName() + "...end");
} catch (Exception e
){
e
.printStackTrace();
}
}).start();
}
}
上面的代码表示,当5个线程都运行到位置3时,其它4个线程才回继续运行,否则其它4个线程将会一直阻塞。
类属性
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
;
private Generation generation
= new Generation();
private int count
;
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
;
}
await()
public int await() throws InterruptedException
, BrokenBarrierException
{
try {
return dowait(false, 0L
);
} catch (TimeoutException toe
) {
throw new Error(toe
);
}
}
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) {
boolean ranAction
= false;
try {
final Runnable command
= barrierCommand
;
if (command
!= null
)
command
.run();
ranAction
= true;
nextGeneration();
return 0;
} finally {
if (!ranAction
)
breakBarrier();
}
}
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 {
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 breakBarrier() {
generation
.broken
= true;
count
= parties
;
trip
.signalAll();
}
private void nextGeneration() {
trip
.signalAll();
count
= parties
;
generation
= new Generation();
}
总结
CyclicBarrier能够实现一组线程阻塞在await()里,直到最后一个线程运行到await()方法时,才会去唤醒前面被阻塞的线程,让前面被阻塞的线程继续运行。
CyclicBarrier与CountDownLatch的异区别:
Countdownlatch是一次性的,计数器的值只能在构造方法中初始化一次,之后没有任何机制再次对其设置值,当CountDownLatch使用完毕后,他不能再次被使用 。CyclicBarrier只能现多个线程到达栅栏处一起运行 。CountDownLatch 不仅能实现一个线程等待多个线程条件成立,还能实现多个线程等待一个线程条件成立。