线程-龟兔赛跑

实现龟兔赛跑,使用多线来完成

提示:
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");
            }
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值