zoukankan      html  css  js  c++  java
  • 赛马小程序

    赛马小程序

    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);
    	}
    }
    

      

  • 相关阅读:
    【OpenCV学习】XML的读写
    【学术研究基础】聚类分析学习
    【OpenCV学习】Laplace变换(视频边界检测)
    【OpenCV学习】DFT变换
    【英语天天读】生命的起跑线
    【OpenCV学习】yml的读取
    【OpenCV学习】Kmean均值聚类对图片进行减色处理
    【英语天天读】born to win
    WinFrom 中 label背景透明
    dev GridControl双击行事件
  • 原文地址:https://www.cnblogs.com/--zz/p/9665738.html
Copyright © 2011-2022 走看看