1.需求:每隔两移输出一次pop
一. public static void main(String[] args){
class myTimerTask extends TimerTask{
new Timer.schedule(new myTimerTask (){
Run(){
System.out.println("pop!");
}
},2000)
}
new Timer().schedule(new myTimerTask (),2000);
while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2.需求:两移与四移间隔输出
二.
public class traditionalTimerTest {
private static int count = 0;
public static void main(String[] args) {
class myTimerTask extends TimerTask{
public void run() {
count =(count+1)%2;
System.out.println("bpping");
new Timer().schedule( new myTimerTask() /*new TimerTask(){
public void run() {
System.out.println("apping");
}
}*/, 2000+2000*count);
}
}
new Timer().schedule(new myTimerTask(),2000
);
while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
本文详细介绍了如何使用Java的Timer类来创建定时任务,实现每隔两秒和四秒间隔输出特定信息,包括定义自定义的TimerTask类和使用schedule方法设置定时任务。
5万+

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



