java定时器

来源:互联网 发布:人工智能李开复读后感 编辑:程序博客网 时间:2024/05/21 06:51

import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class Demo01 {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("boom!");new Timer().schedule(new MyTimerTask(), 1000+3000*count);}}//每隔2秒钟创建一个匿名的MyTimerTask对象new Timer().schedule(new MyTimerTask(), 2000);new Thread() {public void run() {while(true) {System.out.println(new Date().getSeconds());try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}.start();}}
运行结果:
1920boom!21222324boom!25boom!26272829boom!30boom!31323334boom!35boom!