Timer的使用如下:
1.先定義TimerTask執行或顯示的內容.
2.再建立Timer的物件去schedule計時器.
Timer的使用有兩種:
1.單獨建立一個類別extends TimerTask.
2.在同一個類別內建立匿名類別運行.
範例:
1.
--------------第一個類別開始---------------------
import java.util.*;
public class tTimer extends TimerTask
{
public void run()
{
System.out.println("每2秒顯示1次!");
}
}
--------------第一個類別結束---------------------
--------------第二個類別開始---------------------
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Timer timer = new Timer();
timer.schedule(new DateTask(), 5000);
System.out.println("現在時間:" + new Date());
try{
Thread.sleep(8000);
}
catch(InterruptedException e) {
}
timer.cancel();
}
}
--------------第二個類別結束---------------------
2.
public class exam1
{
Timer t=new Timer();
public static void main(String[] args)
{
exam1 ex=new exam1();
ex.timers();
try
{
Thread.sleep(30000);
}
catch(Exception e)
{
}
ex.t.cancel();
}
public void timers()
{
TimerTask tt=new TimerTask()
{
public void run()
{
System.out.println("2秒一次!");
}
};
t.schedule(tt,1000,2000);
}
}