CyclicBarrier

在javaSE5中,CyclicBarrier是一个同步辅助类,允许一组线程相互等待直到全部到达某个“屏障".它是循环的

用在你希望创建一组人物,它们并行地执行,在下一个步骤之前同时等待,直到之前所有的人物都完成,以保证它们可以一致的前进。

下面一个小例子:赛马仿真

package com.my.thread.concurrent;

import java.util.*;
import java.util.concurrent.*;

/**CyclicBarrier可重置计数
 * 赛马仿真
 * @author laotan
 *
 */
public class CyclicBarrierDemo {

	public static void main(String[] args) {
		
		int nHorses = 7 ; //七匹马
		int pause = 100 ;
		new HorseRace(nHorses, pause) ;
	}
}

class Horse implements Runnable {
	
	private static int counter = 0 ;
	private final int id = counter ++ ;
	private int strides =0 ;
	private static Random rand = new Random(47) ;
	private static CyclicBarrier barrier ;
	
	public Horse(CyclicBarrier cb) {
		this.barrier = cb ;
	}
	
	public synchronized int getStrides() {
		return strides ;
	}
	
	public void run() {
		try {
			while(!Thread.interrupted()) {
				synchronized (this) {
				
					strides += rand.nextInt(3) ;
				}
				barrier.await() ;//阻塞,直到计数值为0
			}
		} catch(InterruptedException e) {
			
		} catch(BrokenBarrierException e) {
			throw new RuntimeException(e) ;
		}
	}
	
	public String toString() {
		return "Horse " + id + " " ;
	}
	
	public String tracks() {//仿真奔跑
		StringBuilder s = new StringBuilder() ;
		for(int i=0; i<getStrides(); i++)
			s.append("*") ;
		s.append(id) ;
		return s.toString() ;
	}
}

class HorseRace {
	
	public static final int FINISHI_LINE = 70 ;//赛程
	private List<Horse> horses = new ArrayList<Horse>() ;
	private CyclicBarrier barrier ;
	private ExecutorService ex = Executors.newCachedThreadPool() ;
	/**
	 * 
	 * @param nHorses:参与比赛的数目
	 * @param pause:赛程
	 */
	public HorseRace(int nHorses, final int pause) {
		barrier = new CyclicBarrier(nHorses, new Runnable() {
			//向CyclicBarrier提供一个“屏障", 当计数值到达0时自动执行,并且是可以循环的,直到线程关闭
			public void run() {
				StringBuilder s = new StringBuilder() ;
				for(int i=0; i< FINISHI_LINE; i++)
					s.append("=") ;
				System.out.println(s);
				for(Horse h : horses)
					System.out.println(h.tracks());
				for(Horse h : horses) {
					if(h.getStrides() >= FINISHI_LINE) {
						System.out.println(h + "won!");
						ex.shutdownNow() ;
						return ;
					}
					try {
						TimeUnit.MILLISECONDS.sleep(pause) ;
					} catch(InterruptedException e) {
						System.out.println("Barrier-action sleep interrupted");
					}
				}
			}
		}) ;
		for(int i=0; i<nHorses; i++) {
			Horse h = new Horse(barrier) ;
			horses.add(h) ;
			ex.execute(h) ;
		}
	}
}
 

你可能感兴趣的:(多线程,仿真赛马)