Thinking inJava学习笔记 HorseRace.java

HorseRace.java

每个horse每走一步,都会停下来等待其他horse完成这一步操作

cyclicBarrier的线程会在每一步所有horse完成操作后执行一次

package com.test.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class HorseRace {
	static final int FINISH_LINE=75;
	private List horses=new ArrayList();
	private ExecutorService exec=Executors.newCachedThreadPool();
	private CyclicBarrier barrier;
	public HorseRace(int nHorses, final int pause){
	
	/*CyclicBarrier that will trip when the
     * given number of parties (threads) are waiting upon it, and which
     * will execute the given barrier action when the barrier is tripped,
     * performed by the last thread entering the barrier.
     */
		barrier=new CyclicBarrier(nHorses,new Runnable(){
			public void run(){
				StringBuilder sb=new StringBuilder();
				for(int i=0;i


你可能感兴趣的:(并发多线程)