//注意 :定时任务中,主线程会新开一个线程, timer定时任务中是同一个线程对象/*
*因此在timer中是单线程执行的,故此这个线程安全的 sched方法中还存在synchronized()代码块进行加锁
*/publicstaticvoidmain(String[] args ){//创建定时对象Timer timer =newTimer();//启动定时任务//参数1:执行的任务。//参数2 :任务开始时间//参数3:周期执行任务的间隔时间
timer.schedule(newTimerTask(){@Overridepublicvoidrun(){System.out.println(Thread.currentThread().getName()+"The timer task was executed at now ");}},newDate());System.out.println(Thread.currentThread().getName()+"Main thread");}
2.springboot基于Timer封装的定时任务
# spring boot 本身就对该定时任务类进行了封装,因此只要进行相关的注解声明就可进行使用
@Configration//表示这个一个配置类,spring进行自动装配@EnableScheduling//表识这个类是一个定时任务类publicclassMyTash{@Scheduled(cron="*****?")//表示这是一个定时任务方法publicvoidexecuteTask(){System.out.println("this is springboot to base Timer's timer ");}}