java练习(16.08.03)龟兔赛跑问题

题目详情

龟兔赛跑的故事大家都听过,请采用线程的知识,编写代码作比较。 
具体要求如下: 
1、乌龟和兔子各自一个线程。 
2、乌龟每步跑1厘米,兔子每步跳100厘米。 
3、兔子每跑到第100步的时候,会休息0.001秒; 
4、问:50000厘米比赛谁获胜?

实现代码

实现思路:用一个Player类创建出乌龟和兔子这两个线程来“跑”50000厘米,在创建一个Judgement类里判断谁赢

Player类,实现Runable接口,用来跑步

package fgb;

public class Player implements Runnable {
	// 步速
	private int pace;
	// 步数
	private int n = 0;
	// 休息间隔
	private int interval;
	// 休息时间
	private int restTime;
	private int goal = 50000;
	/*
	 * 步速为pace
	 * 每interval步休息restTime毫秒
	 */
	public Player(int pace, int interval, int restTime) {
		// TODO Auto-generated constructor stub
		this.interval = interval;
		this.restTime = restTime;
		this.pace = pace;
	}

	@SuppressWarnings("static-access")
	@Override
	public void run() {
		for (int distance = 0; distance < goal; n++) {
			//每跑interval步休息一次
			if (n % interval == 0) {
				try {
					Thread.currentThread().sleep(restTime);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			distance += pace;
		}
		System.out.println(Thread.currentThread().getName() + "到达终点");
		System.out.println("总共跑了" + n + "步");
		//跑完后用finish方法告诉裁判
		Judgement.finish(Thread.currentThread().getName());
	}
}

Judgement类:裁判,用于判断输赢以及输出比赛结果 

package fgb;

public class Judgement extends Thread{
	private static StringBuffer string=new StringBuffer();
	public static void finish(String name){
		string.append(name);
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		//super.run();
		while(Judgement.string.length()<4){}
		System.out.println("——————————————————————————\n比赛结果:");
		System.out.print(Judgement.string.substring(0,2));
		System.out.println("赢了"+string.substring(2));
		Judgement.string=new StringBuffer();
	}
}

Game类:代表一场比赛

package fgb;

public class Game {
	public static void main(String[] args) {
		Thread tortoise=new Thread(new Player(1,50000,0),"乌龟");
		Thread rabbit=new Thread(new Player(100,100,1),"兔子");
		Judgement judgement=new Judgement();
		judgement.start();
		tortoise.start();
		rabbit.start();
	}
}
运行结果:
乌龟到达终点
总共跑了50000步
兔子到达终点
总共跑了500步
——————————————————————————
比赛结果:
乌龟赢了兔子


说明

因为乌龟不休息,所以把它看成跑完50000步后才休息
为了让裁判线程能及时判断到比赛结果,所以先让裁判线程start

你可能感兴趣的:(java)