上一篇博客当中,利用栈对Timer和TimerTask进行了封装,在实际运用的当中觉得很好用,这次增加了运行过程中的状态信息。
具体代码如下所示:
public class MyTimer { private MyTimerTask task; private int date; private long period; private StacktaskStack; 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 (); 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; } }}