java多线程之CyclicBarrier使用

应用场景 
在某种需求中,比如一个大型的任务,常常需要分配好多子任务去执行,只有当所有子任务都执行完成时候,才能执行主任务,这时候,就可以选择CyclicBarrier了。例(选手赛跑)

 

 

package com.client;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		CyclicBarrier barrier = new CyclicBarrier(5);
		ExecutorService service = Executors.newFixedThreadPool(5);
		service.submit(new Thread(new Runner(barrier,"选手1")));
		service.submit(new Thread(new Runner(barrier,"选手2")));
		service.submit(new Thread(new Runner(barrier,"选手3")));
		service.submit(new Thread(new Runner(barrier,"选手4")));
		service.submit(new Thread(new Runner(barrier,"选手5")));
		service.shutdown();
	}
}
	
	class Runner implements  Runnable{
		// 一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)
		private CyclicBarrier barrier;
		private String name;

		public Runner(CyclicBarrier barrier, String name) {
			this.barrier = barrier;
			this.name = name;
		}
		@Override
		public void run() {
			try {
				Thread.sleep(1000*(new Random().nextInt(8)));
				System.out.println(name+" 准备好了...");
				 // barrier的await方法,在所有参与者都已经在此 barrier 上调用 await 方法之前,将一直等待。
				barrier.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
			System.out.println(name + " 开始!");
		}
}

 

你可能感兴趣的:(Cyclicbarrier)