定时器

import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;

public class UsingTimer{
    static class MyTimerTask extends TimerTask{
        private int taskId ;
        
        public MyTimerTask(int taskId){
            this.taskId = taskId ;
            }
            
        public void run(){
            System.out.println("taskId["+this.taskId+"] at time["+System.currentTimeMillis()+"]");
            }
        }
    public static void main(String[] args){
        Timer timer = new Timer();
        
        MyTimerTask task1 = new MyTimerTask(1);
        timer.schedule(task1, 200);
        
        MyTimerTask task2 = new MyTimerTask(2);
        Date Date = new Date(System.currentTimeMillis()+1000);
        timer.schedule(task2, Date);
        
        MyTimerTask task3 = new MyTimerTask(3);
        timer.schedule(task3, 200, 500);
        
        try{
            Thread.sleep(2000);
        }catch(InterruptedException e){
            e.printStackTrace();
            }
            
        timer.cancel();    
        System.out.println("timer canceled!");
        }
    }

运行结果:

G:\maul keyboard\thread\timer>javac UsingTimer.java

G:\maul keyboard\thread\timer>java UsingTimer
taskId[1] at time[1535889634267]
taskId[3] at time[1535889634267]
taskId[3] at time[1535889634767]
taskId[2] at time[1535889635067]
taskId[3] at time[1535889635267]
taskId[3] at time[1535889635768]
timer canceled!

G:\maul keyboard\thread\timer>

posted @ 2018-09-02 20:09  celineluo  阅读(109)  评论(0编辑  收藏  举报