版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014252478/article/details/83587313
传统定时器技术:
(1)Timer类
Timer下的方法有以下几个:
返回值 | 方法名 |
void | schedule(TimerTask task, long delay) |
void | schedule(TimerTask task, long delay, long period) |
void | schedule(TimerTask task, Date time) |
void | schedule(TimerTask task, Date firstTime, long period) |
创建一个普通定时器:
public static void main(String[] args){
new timer.schedule(new timeTask(){
@Override
public void run(){
System.out.println("boom----");
}
}, 2000, 3000);
while(true){
System.out.println("boom-----");
}
}
定时器套定时器:
public static void main(String[] args){
class myTask extends TimerTask{
@Override
public void run(){
System.out.println("boo-----");
new timer().schedule(new myTask(), 300); //定时器中嵌入一个定时器,循环
}
}
new timer().schedule(new myTask(), 300);
while(true){ //打印秒钟,一秒输出一次
System.out.println(new Date().getSeconds);
try{
Thread.sleep(1000);
} catch(Exception e){
e.printStackTrace();
}
}
}
(2)Thread创建线程方式延时
public static void main(String[] args){
final long internalTime = 1000;
Runnable runnable = new Runnable(){
@Override
public void run(){
while(true){
System.out.println("-------线程");
try{
Thread.sleep(1000);
} catch(Exception e){
e.printStackTrace();
}
}
}
};
Thread thread1 = new Thread(runnable);
thread.start();
}
(3)ScheduleExcutorService(最理想的定时方式)
public static void main(String[] args){
Runnable runnable = new Runnable(){
@Override
public void run(){
......
}
};
ScheduleExcutorService scheduleExcutorService = new ScheduleExcutorService();
//首次延时100秒,1秒间隔循环执行
scheduleExcutorService.scheduleAtFixedRate(runnable, 100, 1, TIME.SECONDS);
}