简单的实现java多线程——龟兔赛跑

题目:

实现龟兔赛跑
提示:可以采用Math.random()取得0~1之间的随机数模拟比赛进程, 如总距离为100米,在随机数00.3之间代表兔子跑,每次跑2米,在0.31之间代表乌龟跑,每次跑1 米,先跑完100米者为胜利者
结构:
Race类:产生RabbitAndTurtle的两个实例,分别代表兔子和乌龟
RabbitAndTurtle类:继承Thread类,实现赛跑的逻辑

代码实现:

Rabbit类

package ch08;

public class Rabbit extends Thread {
	private int RabbitDistance;
	
	@Override
	public void run() {
		RabbitDistance = 0;
		while (RabbitDistance < 100) {
			double i = Math.random();
			if (i > 0.3 && i < 1.0) {
				RabbitDistance++;
				System.out.println(getName()+"已经跑了" + RabbitDistance);
			}
		}
		System.out.println("-----------Rabbit获胜-----------");
	}
}

Turtle类

package ch08;

public class Turtle extends Thread {
	private int TurtleDistance;
	
	@Override
	public void run() {
		while (TurtleDistance < 100) {
			double i = Math.random();
			if (i > 0 && i < 0.3) {
				TurtleDistance++;
				System.out.println(getName()+"已经跑了" + TurtleDistance);
				}
		}
		System.out.println("-----------Turtle获胜-----------");
	}
}

RabbitAndTurtle类

package ch08;

public class RabbitAndTurtle extends Thread {
	public static void main(String[] args) {
	    Thread rabbit = new Rabbit();
	    Thread turtle = new Turtle();
	    rabbit.setName("小白兔");
	    turtle.setName("小乌龟");
		rabbit.start();
		turtle.start();
	}
}

你可能感兴趣的:(java基础,java多线程,龟兔赛跑,java)