下面是示例程序:
ExecutorService service = Executors.newCachedThreadPool();
final CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
for(int i = 0;i<3;i++){
Runnable runnable = new Runnable(){
Random random = new Random();
@Override
public void run() {
try {
Thread.sleep(random.nextInt(5000));
System.out.println("point 1:"+Thread.currentThread().getName()+" execute complate.");
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
try {
Thread.sleep(random.nextInt(5000));
System.out.println("point 2:"+Thread.currentThread().getName()+" execute complate.");
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
try {
Thread.sleep(random.nextInt(5000));
System.out.println("point 3:"+Thread.currentThread().getName()+" execute complate.");
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
try {
Thread.sleep(random.nextInt(5000));
System.out.println("point 4:"+Thread.currentThread().getName()+" execute complate.");
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
};
service.execute(runnable);
//service.shutdown();
}
執行結果:point 1:pool-1-thread-3 execute complate.
point 1:pool-1-thread-2 execute complate.
point 1:pool-1-thread-1 execute complate.
point 2:pool-1-thread-2 execute complate.
point 2:pool-1-thread-1 execute complate.
point 2:pool-1-thread-3 execute complate.
point 3:pool-1-thread-3 execute complate.
point 3:pool-1-thread-1 execute complate.
point 3:pool-1-thread-2 execute complate.
point 4:pool-1-thread-1 execute complate.
point 4:pool-1-thread-2 execute complate.
point 4:pool-1-thread-3 execute complate.
可以看到,到達麼一個點的順序可能不固定,但是沒有說一個線程纔到達point1的時候,另外一個線程已經達到point2了,即大家共同達到一個點之後纔會繼續往下執行。