package com.icss.thread;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TraditionalTimerTest {
private static int count = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
/*new Timer().schedule(new TimerTask(){
@Override
public void run() {
System.out.println("bombing");
}
}, 1000,3000);*/
class MyTimerTask extends TimerTask {
@Override
public void run() {
count = (count+1)%2;
System.out.println("bombing");
new Timer().schedule(/*new TimerTask(){
@Override
public void run() {
System.out.println("bombing");
}
}*//*this*/new MyTimerTask(), 2000+2000*count);
}
}
new Timer().schedule(new MyTimerTask(), 2000/*,3000*/);
while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
System.out.println("延迟");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TraditionalTimerTest {
private static int count = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
/*new Timer().schedule(new TimerTask(){
@Override
public void run() {
System.out.println("bombing");
}
}, 1000,3000);*/
class MyTimerTask extends TimerTask {
@Override
public void run() {
count = (count+1)%2;
System.out.println("bombing");
new Timer().schedule(/*new TimerTask(){
@Override
public void run() {
System.out.println("bombing");
}
}*//*this*/new MyTimerTask(), 2000+2000*count);
}
}
new Timer().schedule(new MyTimerTask(), 2000/*,3000*/);
while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
System.out.println("延迟");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
本文探讨了传统定时器在复杂场景下的高级应用,通过创建自定义定时任务类,实现定时任务之间的递归调用,并在每次执行后更新计数器,展示了如何利用Java Timer API进行更灵活的任务调度。
486

被折叠的 条评论
为什么被折叠?



