实现龟兔赛跑,使用多线来完成
提示:
1.可以采用Math.random()取得0~1之间的随机数模拟比赛进程
2.如总距离为100米,在随机数0~0.3之间代表兔子跑,每次跑2米,在0.3~1之间代表乌龟跑,每次跑1米
4.先跑完100米者为胜利者
public class work2 { public static void main(String[] args) { new TurtleAndRabbit("乌龟").start(); new TurtleAndRabbit("兔子").start(); } } class TurtleAndRabbit extends Thread{ public TurtleAndRabbit(String name) { super(name); } public static final int INSTANCE = 100; public int currentInstance; public static boolean flag = true; @Override public void run() { while (flag){ double random = Math.random(); if (random <= 0.3 && this.getName().equals("兔子")){ currentInstance += 2; System.out.println(this.getName() + "跑了" + currentInstance + "米"); } if (random > 0.3 && this.getName().equals("乌龟")){ currentInstance += 1; System.out.println(this.getName() + "跑了" + currentInstance + "米"); } if(currentInstance == INSTANCE){ flag = false; System.out.println(this.getName() + "win"); } } } }