- * 目的:了解CyclicBarrier
- * CyclicBarrier作用:
- * 一组线程相互等待,知道都到达了某个公共屏障,继续往下走。
- */
- public class CyclicBarrierTest {
- public static void main(String[] args) {
-
- ExecutorService threadPool = Executors.newCachedThreadPool();
- final CyclicBarrier barrier = new CyclicBarrier(3);
-
- for(int i=0;i<3;i++){
- final int n = i;
- Runnable runnable = new Runnable(){
- public void run() {
- try {
- Thread.sleep(1000*n);
- System.out.println(Thread.currentThread().getName()+
- "到达了A地点,正坐在马路上看着短裙美女等待着其他人,"+"当前已有人数"+barrier.getNumberWaiting());
- barrier.await();
-
- Thread.sleep(1000*n);
- System.out.println(Thread.currentThread().getName()+
- "到达了B地点,正在咖啡厅搭讪美女等待着其他人"+"当前已有人数"+barrier.getNumberWaiting());
- barrier.await();
- Thread.sleep(1000*n);
- System.out.println(Thread.currentThread().getName()+
- "到达了C地点,正在和刚刚搭讪到的美女电话聊着天等待着其他人"+"当前已有人数"+barrier.getNumberWaiting());
- barrier.await();
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (BrokenBarrierException e) {
- e.printStackTrace();
- }
- }
- };
- threadPool.execute(runnable);
- }
- threadPool.shutdown();
- }
- }
复制代码 |
|