多线程案例-龟兔赛跑

1)首先来个赛道距离,然后要离终点越来越近

2)判断比赛是否结束

3)打印出胜利者

4)龟兔赛跑开始

5)故事中是乌龟赢,兔子需要睡觉,所有我们来模拟兔子睡觉

6)终于,乌龟赢了比赛。

 1 public class Race implements Runnable {
 2 
 3     // 胜利者,,因为只有一个,所以写成static的
 4     private static String winner;
 5     @Override
 6     public void run() {
 7 
 8         for (int i = 0; i <= 100  ;  i++) {
 9             if(Thread.currentThread().getName().equals("兔子")) {
10                 try {
11                     Thread.sleep(10);
12                 } catch (InterruptedException e) {
13                     e.printStackTrace();
14                 }
15             }
16             // 判断比赛是否结束
17             boolean flag = gameOver(i);
18             // 如果比赛结束,就停止程序
19             if (flag) {
20                 break;
21             }
22             System.out.println( Thread.currentThread().getName() + "走了" + i + "步");
23         }
24 
25     }
26 
27     // 判断是否完成比赛
28     private boolean gameOver (int steps) {
29         // 判断是否有胜利者
30         if (winner != null) { // 已经存在胜利者
31             return true;
32         } else {
33             if (steps >= 100) {
34                 winner = Thread.currentThread().getName();
35                 System.out.println("winner is " + winner);
36                 return true;
37             }
38         }
39         return  false;
40     }
41 
42     public static void main(String[] args) {
43         Race race = new Race();
44         new Thread(race,"乌龟").start(); // 乌龟跑起来
45         new Thread(race,"兔子").start(); // 兔子跑起来
46 
47     }
48 
49 
50 }

 

posted on 2021-04-02 16:46  Love&Share  阅读(107)  评论(0编辑  收藏  举报

导航