java定時器

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();
	}
}
運行結果:
19
20
boom!
21
22
23
24
boom!
25
boom!
26
27
28
29
boom!
30
boom!
31
32
33
34
boom!
35
boom!




發佈了21 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章