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

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

*/
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TaskContraller {

    public static void main(String[] args) {
        //初始化
        ConcurrentHashMap<String, WalkingTask> walktaskmap = new ConcurrentHashMap<String, WalkingTask>();
        Player tom = new Player("Tom", 1000, 2000, 20);
        Player kitty = new Player("kitty", 800, 3000, 10);
        walktaskmap.put("Tom", new WalkingTask(tom));
        walktaskmap.put("kitty", new WalkingTask(kitty));

        System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date(
                System.currentTimeMillis())));
         //定义一个容量为50个线程的线程池
          final ScheduledExecutorService pool = Executors
                .newScheduledThreadPool(50);

        Iterator<String> ite = walktaskmap.keySet().iterator();
        while (ite.hasNext()) {
            String name = ite.next();
            WalkingTask walkingTask = walktaskmap.get(name);
            System.out.println(name + " is ready to walking...!");
            //立即执行任务,开始比赛
            pool.execute(walkingTask);
            //延时执行任务,停止比赛
            StopTask stopTask = new StopTask(walktaskmap, name);
            pool.schedule(stopTask, walkingTask.getPlayer().getTotalSeconds(),
                    TimeUnit.SECONDS);
        }

        System.out.println("main thread....");
    }
}
/**
   竞走任务类
*/
class WalkingTask implements Runnable {
    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) {
        // TODO Auto-generated constructor stub
        this.player = player;
    }

    @Override
    public void run() {
        for (int i = 0; i <= this.player.getMeters(); i++) {
            if (this.isStop) {
                break;
            }
            System.out.println(this.player.getName() + " run:" + i + " m!");
            try {
                Thread.sleep(this.player.getMillsecond());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 中止比赛任务类
*/
class StopTask implements Runnable {
    private final String key; //被中止的运动员姓名
    private final ConcurrentHashMap<String, WalkingTask> mytasks;

    public StopTask(ConcurrentHashMap<String, WalkingTask> 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;//总赛时

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

    }

    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;
    }

}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。