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!