多线程实现龟兔赛跑

public class Main {
    //设置比赛的总距离
    private static int end =1000;
    //记录乌龟和兔子跑过的距离
    private static int start1 =0;
    private static int start2 =0;
    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    synchronized (Main.class) {
                        start1 = start1 + 5;
                        System.out.println("兔子跑了" + start1 + "米");
                        if (start1 == end) {
                            System.out.println("兔子到达了终点");
                            System.out.println("兔子取得了胜利");
                            System.out.println("乌龟跑到了"+start2+"米");
                            System.exit(0);
                            break;
                        }
                    }
                    if (start1 % 20 == 0) {
                        try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                    }
                    //}
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    synchronized (Main.class) {
                        start2 = start2 + 1;
                        System.out.println("乌龟跑了" + start2 + "米");
                        if (start2 == end) {
                            System.out.println("乌龟到达了终点");
                            System.out.println("乌龟取得了胜利");
                            System.out.println("兔子跑到了"+start1+"米");
                            System.exit(0);
                            break;
                        }
                    }
                    if (start2 % 100 == 0) {
                        try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                    }
                }
            }
        }).start();
    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值