CyclicBarrier


public static void test2(){
		ExecutorService executorService=Executors.newCachedThreadPool();
		final CyclicBarrier cyclicBarrier=new CyclicBarrier(3);
		for(int i=0;i<3;i++){
			Runnable runnable=new Runnable(){
				public void run(){
					try {
						Thread.sleep((long)(Math.random()*10000));
						System.out.println(Thread.currentThread().getName()+"到达");
						cyclicBarrier.await();
						Thread.sleep((long)(Math.random()*10000));
						System.out.println(Thread.currentThread().getName()+"到达");
						cyclicBarrier.await();
						
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (BrokenBarrierException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
			executorService.execute(runnable);
		}
		executorService.shutdown();
	}

/** 输出 

pool-1-thread-2到达
pool-1-thread-3到达
pool-1-thread-1到达
pool-1-thread-3到达
pool-1-thread-1到达
pool-1-thread-2到达

**/

你可能感兴趣的:(java)