定时器的编写

 1 package cn.sp.thread;
 2 
 3 
 4 import java.util.Date;
 5 import java.util.Timer;
 6 import java.util.TimerTask;
 7 
 8 /**
 9  * Created by 2YSP on 2017/10/14.
10  * 定时器
11  */
12 public class TraditionalTimer {
13 
14     private static int count = 0;
15 
16     public static void main(String[] args) {
17 //        new Timer().schedule(new TimerTask() {
18 //            @Override
19 //            public void run() {
20 //                System.out.println("boom!");
21 //            }
22 //        },10000);//10秒后触发
23 
24         /********间隔时间为2秒和4秒轮流执行************/
25         class MyTimerTask extends TimerTask{
26             @Override
27             public void run() {
28                 count = (count+1)%2;//1 0 1 0
29                 System.out.println(new Date().getSeconds());
30                 System.out.println("boom!");
31                 new Timer().schedule(new MyTimerTask(),2000+2000*count);
32             }
33         }
34 
35         new Timer().schedule(new MyTimerTask(),2000);
36 
37 //        while (true){
38 //            System.out.println(new Date().getSeconds());
39 //            try {
40 //                Thread.sleep(1000);
41 //            } catch (InterruptedException e) {
42 //                e.printStackTrace();
43 //            }
44 //        }
45     }
46 }

执行结果:

之间学习并发编程并没有注意到Timer这个类,可能是被摒弃了吧。毕竟现在项目中的定时任务,可以使用组件quartz或者spring框架自带的Task。

我怀疑后面两种也是基于该类实现吧。

原文地址:https://www.cnblogs.com/2YSP/p/7695937.html