• 赛马小程序


    赛马小程序

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

      

  • 相关阅读:
    [C和指针]第一部分
    [Effective Java]第十章 并发
    [C程序设计语言]第五部分
    [C程序设计语言]第四部分
    git clone速度太慢解决方案
    Golang使用Redis
    删除校管理员的多余数据
    jQuery ajax同步的替换方法,使用 $.Deferred()对象
    打包并删除临时文件
    通过vjudge刷Uva的题目(解决Uva网站打开慢的问题)
  • 原文地址:https://www.cnblogs.com/--zz/p/9665738.html
Copyright © 2020-2023  润新知