多线程龟兔赛跑--Callable版本

Cabllable实现龟兔赛跑

package cn.hlooc;

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

public class RaceTest implements Callable<String> {

    private final Runner runner;

    public RaceTest(Runner runner) {
        this.runner = runner;
    }

    @Override

    public String call() {
        return runner.raceRun();
    }

}

interface Runner {

    String raceRun();
}

class Winner {

    private static String win;

    public static void setWinner(String name) {

        if (win == null) {
            win = name;
            System.out.println(name + " is Winner.");
        }

    }


    public static String getWinner() {
        return win;
    }

}

class Rabbit implements Runner {

    @Override
    public String raceRun() {
        String name = Rabbit.class.getSimpleName();
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + ": Run " + i + " step.");
        }
        Winner.setWinner(name);
        return name;
    }
}

class Tortoise implements Runner {

    @Override
    public String raceRun() {
        String name = Tortoise.class.getSimpleName();
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + ": Run " + i + " step.");
        }
        Winner.setWinner(name);
        return name;
    }
}

class M {

    public static void main(String[] args) {
        List<Runner> runnerList = new ArrayList<>(2);
        runnerList.add(new Rabbit());
        runnerList.add(new Tortoise());
        ExecutorService es = Executors.newFixedThreadPool(2);
        List<Future<String>> fs = new ArrayList<>();
        runnerList.forEach(runner -> fs.add(es.submit(new RaceTest(runner))));
        es.shutdown();
        fs.forEach(future -> {
            try {
                System.out.println(future.get() + " has done.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}

上一篇:程序开发BUG修复记录1


下一篇:flutter .g.dart文件