线程中的定时器:
一、首先想有一个定时器需要创建一个Timer类,启动定时器是调用Timer类中的schedule()方法 翻译过来是调度,
package cn.itcast.heima2;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* 传统定时器类
* @author asus
*
*/
public class TreaditionalTimerTest {
public static class MyTimerTask extends TimerTask {
static int count = 0;
@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!");
}
}*/ new MyTimerTask() , 2000+2000*count);
}
}
/**
* 定义一个炸弹,先2秒炸一次,再4秒炸一次,再两秒....一直循环
*/
public static void test2(){
new Timer().schedule(new MyTimerTask(), 2000);
while(true){
//为了显示上面什么时候炸的一个循环
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void test1(){
//定义一个定时器 schedule(Task 所需要执行的代码 TimerTask是这个类,需要重写run方法,
// time 这个是定义什么时候执行上面的对象方法,单位是以毫秒为单位,
// 如果time中有两个参数,证明在指定的时间内会执行两次)方法的单词是调度的意思
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.out.println("bombing!");
}
//这个的意思是先在10秒以后执行一次上面的代码,之后的每三秒执行一次
}, 10000,3000);
while(true){
//为了显示上面什么时候炸的一个循环
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// test1();
test2();
}
}

本文介绍如何使用Java中的Timer类创建并运行定时任务。通过具体的代码示例,展示了如何定义一个定时任务并设置其执行间隔,包括一次性任务和周期性任务的实现。

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



