Timer和TimerTask的使用--2

上一篇博客当中,利用栈对Timer和TimerTask进行了封装,在实际运用的当中觉得很好用,这次增加了运行过程中的状态信息。

具体代码如下所示:

public class MyTimer {

    private MyTimerTask task;
    private int date;
    private long period;
    private Stack<MyTimerTask> taskStack;
    private Timer timer;

    private int state;

    public static int READY = 0;
    public static int RUNNING = 1;
    public static int PAUSE = 2;
    public static int STOP = 3;

    public MyTimer(TimerTask timerTask, int date, int period){
        task=new MyTimerTask(timerTask);
        this.date=date;
        this.period=period;
        timer=new Timer();
        taskStack=new Stack<MyTimerTask>();
        state = READY ;
    }

    public void start() {
        if(state == READY){//准备状态
            timer.schedule(task, date, period);
        }else if(state == PAUSE){//暂停状态
            resume();
        }else{
            return ;
        }
        state = RUNNING ;
    }

    public void stop() {
        try {
            timer.cancel();
            taskStack.clear();
            task.cancel();
        }catch(Exception e){
            e.printStackTrace();
        }
        state = STOP;
    }

    public void pause() {
        if(state == RUNNING) {
            //使用栈保存当前的任务
            taskStack.push(new MyTimerTask(task.getCurrentTask()));
            task.cancel();
            state = PAUSE;
        }
    }

    private void resume() {
        try {
            //出栈,恢复保存的任务
            task = taskStack.pop();
            timer.schedule(task, 0, period);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public int getState(){
        return this.state;
    }

    private class MyTimerTask extends TimerTask{

        private TimerTask task;

        public MyTimerTask(TimerTask task){
            this.task=task;
        }

        @Override
        public void run() {
            task.run();
        }

        public TimerTask getCurrentTask(){
            return task;
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值