赛马小程序

赛马小程序

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

class Horse implements Runnable{
	private static int counter = 0;
	private final int id = counter++;
	private int strides = 0;
	private static Random random = new Random(47);
	private static CyclicBarrier barrier;
	public Horse(CyclicBarrier b) {
		barrier = b;
	}
	public synchronized int getStrides() {
		return strides;
	}
	public void run() {
		try {
			while(!Thread.interrupted()) {
				synchronized (this) {
					strides += random.nextInt(3);
				}
				barrier.await();
			}
		}catch (InterruptedException e) {
			// TODO: handle exception
		}catch (BrokenBarrierException e) {
			throw new RuntimeException(e);
		}
	}
	public String toString() {
		return "Horse: " + id + " " ;
	}
	public String tracks() {
		StringBuffer s = new StringBuffer();
		for(int i=0;i<getStrides();i++) {
			s.append("*");
		}
		s.append(id);
		return s.toString();
	}
}

public class Restaurant{
	static final int FINISH_LINE = 75;
	private List<Horse> horses = new ArrayList<Horse>();
	private ExecutorService executorService = Executors.newCachedThreadPool();
	private CyclicBarrier barrier;
	public Restaurant(int nHorses,final int pause) {
		barrier = new CyclicBarrier(nHorses,new Runnable( ) {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				StringBuffer stringBuffer = new StringBuffer();
				for(int i=0;i<FINISH_LINE;i++)
					stringBuffer.append("=");
				System.out.println(stringBuffer);
				for(Horse horse: horses) {
					System.out.println(horse.tracks());
				}
				for(Horse horse: horses) {
					if(horse.getStrides() >= FINISH_LINE) {
						System.out.println(horse + " won");
						executorService.shutdownNow();
						return;
					}
				}
				try {
					TimeUnit.MILLISECONDS.sleep(pause);
					for(int i=0;i<8;i++)
						System.out.println();
				}catch(InterruptedException e) {
					System.out.println("barrier-action sleep interrupted");
				}
			}
		});
		for(int i=0;i<nHorses;i++) {
			Horse horse = new Horse(barrier);
			horses.add(horse);
			executorService.execute(horse);
		}
	}
	public static void main(String[] args) throws Exception {
		int nHorses = 6;
		int pause = 100;
		new Restaurant(nHorses,pause);
	}
}

  

posted @ 2018-09-17 23:51  zz2108828  阅读(834)  评论(0编辑  收藏  举报