hooyantsing's Blog

7_龟兔赛跑

字数统计: 136阅读时长: 1 min
2020/08/20

7 龟兔赛跑

狂神说Java 多线程详解

龟兔赛跑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Race implements Runnable {
private static String winner;

@Override
public void run() {
for (int i = 0; i <= 100; i++) {
boolean flag = gameOver(i);
if(flag){
break;
}
System.out.println(Thread.currentThread().getName() + " 跑了 " + i + " 步");
}
}

private boolean gameOver(int steps){
if(winner != null){
return true;
}
if(steps >= 100){
winner = Thread.currentThread().getName();
System.out.println("winner is " + winner);
return true;
}
return false;
}

public static void main(String[] args) {
// 公共赛道
Race race = new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
CATALOG
  1. 1. 7 龟兔赛跑