Java多线程--龟兔赛跑Callable简单实现
Callable实现龟兔赛跑
线程池使用的Executors.newFixedThreadPool(2)
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;
}
}