定时器:
定时一次任务
public class TraditionalTimerTest {
public static void main(String[] args) throws InterruptedException {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.out.println("定时5秒");
}
}, 5000);
while(true){
System.out.println(new Date().getSeconds());
Thread.sleep(1000);
// System.out.println(System.currentTimeMillis());
}
}
}
定时间隔一定时间执行一次
public class TraditionalTimerTest {
public static void main(String[] args) throws InterruptedException {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.out.println("3秒执行一次");
}
}, 5000,3000);
}
}
方法中调用方法,使用死循环实现定时任务
public class TraditionalTimerTest {
public static void main(String[] args) {
class MyTimerTask extends TimerTask{
@Override
public void run() {
System.out.println("bombing!");
new Timer().schedule(new MyTimerTask(),2000);
}
}
new Timer().schedule(new MyTimerTask(), 4000);
while(true){
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}