三湘古邑

我想在那里最蓝的大海扬帆。

0%

Java多线程--龟兔赛跑Callable简单实现

Callable实现龟兔赛跑

线程池使用的Executors.newFixedThreadPool(2)

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package cn.hlooc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class RaceSimpleTest {

public static void main(String[] args) {
List<String> raceList = new ArrayList<>(2);
raceList.add("Rabbit");
raceList.add("Tortoise");

ExecutorService es = Executors.newFixedThreadPool(2);
List<Future<String>> ft = new ArrayList<>();
raceList.forEach(s -> ft.add(es.submit(new Race(s))));
es.shutdown();
ft.forEach(s -> {
try {
System.out.println(s.get() + " come on.");
} catch (Exception e) {
e.printStackTrace();
}
});
}
}

class Race implements Callable<String> {

static String winner = "";

String name;

public Race(String name) {
this.name = name;
}

@Override
public String call() throws Exception {

for (int i = 0; i < 100; i++) {
//Rabbit want to sleep.
if (name.equalsIgnoreCase("Rabbit") && i == 88) {
Thread.sleep(100);
}
System.out.println(name + " run " + i + " step.");
if (i == 99 && winner.isEmpty()) {
winner = name;
}
}
System.out.println(name + ",Game is over,Winner is " + winner);
return name;
}
}