使用java.util.concurrent包编写一个延时执行的任务

package com.letv.lazybox.task;
/**
     若干参赛者参加竞走比赛,每组比赛有规定不同的全程米数,总赛时长;运动员若在规定赛时未跑完全程则出局;最后输出比赛成绩

*/
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TaskContraller {

    public static void main(String[] args) {
        // 初始化
        ConcurrentHashMap walktaskmap = new ConcurrentHashMap();
        Player tom = new Player("Tom", 10, 2000, 30);
        Player kitty = new Player("kitty", 80, 3000, 10);
        walktaskmap.put("Tom", new WalkingTask(tom));
        walktaskmap.put("kitty", new WalkingTask(kitty));
        // 创建存放结果状态的列表
        List> futureList = new ArrayList>();

        System.out.println("StartTime="
                + new SimpleDateFormat("HH:mm:ss").format(new Date(System
                        .currentTimeMillis())));
        // 创建线程池
        final ScheduledExecutorService pool = Executors
                .newScheduledThreadPool(50);
        Iterator ite = walktaskmap.keySet().iterator();
        while (ite.hasNext()) {
            String name = ite.next();
            WalkingTask walkingTask = walktaskmap.get(name);
            System.out.println(name + " is ready to walking...!");
            // (异步)立即开始执行比赛任务
            Future future = pool.submit(walkingTask);
            // (异步)延时执行停止任务
            StopTask stopTask = new StopTask(walktaskmap, name);
            pool.schedule(stopTask, walkingTask.getPlayer().getTotalSeconds(),
                    TimeUnit.SECONDS);
            futureList.add(future);
        }

        System.out.println(".....main thread....");
        // 异步等待结束输出结果
        try {
            for (Future fu : futureList) {
                Player player = fu.get();
                System.out.println("result-------->\n" + player.toString());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池:当前未完成线程接续执行,不再接受新线程
            pool.shutdown();
        }
    }
}

/**
 * 竞走比赛任务类:有返回值
 */
class WalkingTask implements Callable {
    private boolean isStop = false;// 是否中止比赛
    private Player player;// 运动员

    public boolean isStop() {
        return this.isStop;
    }

    public void setStop(boolean isStop) {
        this.isStop = isStop;
    }

    public Player getPlayer() {
        return this.player;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }

    public WalkingTask(Player player) {
        this.player = player;
    }

    @Override
    public Player call() {

        for (int i = 1; i <= this.player.getMeters(); i++) {
            try {
                Thread.sleep(this.player.getMillsecond());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(this.player.getName() + " run:" + i + " m!");
            if (this.isStop) {
                Result res = new Result(false, i, this.player.getMillsecond()
                        * i / 1000);
                this.player.setResult(res);
                return this.player;
            }
        }
        this.player.setResult(new Result(true, this.player.getMeters(),
                this.player.getMillsecond() * this.player.getMeters() / 1000));
        return this.player;
    }
}

/**
 * 通知比赛中止任务类:无返回值
 */
class StopTask implements Runnable {
    private final String key;// 运动员姓名
    private final ConcurrentHashMap mytasks;

    public StopTask(ConcurrentHashMap mytasks, String name) {
        this.mytasks = mytasks;
        this.key = name;
    }

    @Override
    public void run() {
        this.mytasks.get(this.key).setStop(true);
        String endTime = new SimpleDateFormat("HH:mm:ss").format(new Date(
                System.currentTimeMillis()));
        System.out.println("[ " + this.key + " ] GAME OVER ! EndTime ="
                + endTime);
    }
}

/**
 * 运动员
 */
class Player {
    private String name;// 姓名
    private int meters;// 参赛总里程数
    private int millsecond;// 每跑一米用时
    private int totalSeconds;// 总赛时
    private Result result;// 成绩

    public Player(String name, int meters, int millsecond, int totalSeconds) {
        this.name = name;
        this.meters = meters;
        this.millsecond = millsecond;
        this.totalSeconds = totalSeconds;

    }

    public Result getResult() {
        return this.result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMeters() {
        return this.meters;
    }

    public void setMeters(int meters) {
        this.meters = meters;
    }

    public int getMillsecond() {
        return this.millsecond;
    }

    public void setMillsecond(int millsecond) {
        this.millsecond = millsecond;
    }

    public int getTotalSeconds() {
        return this.totalSeconds;
    }

    public void setTotalSeconds(int totalSeconds) {
        this.totalSeconds = totalSeconds;
    }

    @Override
    public String toString() {
        return "Player [name=" + this.name + ", meters=" + this.meters
                + ", millsecond=" + this.millsecond + ", totalSeconds="
                + this.totalSeconds + ", result=" + this.result.toString()
                + "]";
    }

}

/**
 * 比赛成绩
 */
class Result {
    private boolean finished;// 是否完成
    private int meters;// 跑了多少米
    private int times;// 用时

    public Result(boolean finished, int meters, int times) {
        this.finished = finished;
        this.meters = meters;
        this.times = times;
    }

    public boolean getFinished() {
        return this.finished;
    }

    public void setFinished(boolean finished) {
        this.finished = finished;
    }

    public int getMeters() {
        return this.meters;
    }

    public void setMeters(int meters) {
        this.meters = meters;
    }

    public int getTimes() {
        return this.times;
    }

    public void setTimes(int times) {
        this.times = times;
    }

    @Override
    public String toString() {
        return "Result [finished=" + this.finished + ", meters=" + this.meters
                + ", times=" + this.times + "]";
    }

}


你可能感兴趣的:(使用java.util.concurrent包编写一个延时执行的任务)