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(); } }
多线程实现龟兔赛跑
最新推荐文章于 2023-05-22 00:42:33 发布