循环的路障,可以进行反复的使用。
public class CyclicBarrierTest {
public static void main(String[] args) {
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
final CyclicBarrier barrier = new CyclicBarrier(3);
for (int i = 0; i < 3; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("线程:" + Thread.currentThread().getName() + "即将--到达集合点A");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程:" + Thread.currentThread().getName() + "已经--到达集合点A");
barrier.await();
System.out.println("线程:" + Thread.currentThread().getName() + "即将--到达集合点B");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程:" + Thread.currentThread().getName() + "已经--到达集合点B");
barrier.await();
System.out.println("线程:" + Thread.currentThread().getName() + "即将--到达集合点C");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("线程:" + Thread.currentThread().getName() + "已经--到达集合点C");
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
};
cachedThreadPool.execute(runnable);
}
}
}
如有疑问,请发邮件:[email protected]
github:??https://github.com/wangrui0/