1. 程式人生 > >Java傳統定時器Timer使用

Java傳統定時器Timer使用

radi rgs .get thread trac ets stub 靜態變量 cep

package cn.qy.heima2;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


public class TraditionalTimerTest {
private static int x=0;
public static void main(String[] args) {
// TODO Auto-generated method stub
/* new Timer().schedule(new TimerTask() {
@Override
public void run()

{System.out.println("booming!"); }
}, 10000,3000);*/
// TODO Auto-generated method stub
class Mytimertask extends TimerTask
{
//匿名內部類代碼只能new一次
//內部類 不能 申請 靜態變量
@Override
public void run()
{
x=(x+1)%2;
System.out.println("booming!");
new Timer().schedule(/*new TimerTask() {
public void run()
{System.out.println("booming!"); }
}*/new Mytimertask(),2000+2000*x);
}
}
new Timer().schedule(new Mytimertask(),2000);
while(true)
{
System.out.println(new Date().getSeconds());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Java傳統定時器Timer使用