Cyclic用于线程之间的同步,形象化一点就是说,大家都到达了再一齐继续运行,
相对于CountDownLatch来说,它可以被重用,因为在await到达之后,count会被自动重新初始化。
CyclicBarrier中有两个方法需要注意:
-
await
用于使所有的线程同步到一个点上进行等待,如果要进行下一步,所有的线程一定是在程序中的某一点都在等待,而CountDownLatch就不能保证在同一个起跑线上(CountDownLatch只能保证其他调用countdown方法的线程已经都完成了)。
根据await的return值我们可以针对性的进行功能定制:
the arrival index of the current thread, where index getParties() - 1 indicates the first to arrive and zero indicates the last to arrive -
runnableCommand
CyclicBrrier在初始化的时候可以指定一个Runnable对象,这个对象在所有线程都打到await点,但是还没被释放的时候(也就是大家齐步走之前运行),在这个方法里,我们可以更新一些共同的变量等来同步线程。
public class Worker implements Runnable{
private final CyclicBarrier barrier;
private int count = 0;
Worker(CyclicBarrier barrier){
this.barrier = barrier;
}
@Override
public void run() {
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
doSomething();
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
doSomething();
}
private void doSomething(){
System.out.println("do something "+ (++count));
}
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(11, new Runnable() {
@Override
public void run() {
System.out.println("reach the point");
}
});
for (int i = 0; i < 10; i++) {
new Thread(new Worker(barrier)).start();
}
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("main point1");
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println("main point2");
}
}