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 hread imer>javac UsingTimer.java
G:maul keyboard hread imer>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 hread imer>