在應用開發中,經常需要一些周期性的操作,比如每5分鐘檢查一下新郵件等。對于這樣的操作最方便、高效的實現方式就是使用java.util.Timer工具類。比如下面的代碼每5分鐘檢查一遍是否有新郵件:
package?test.Timer;

import?java.util.Timer;
import?java.util.TimerTask;


public?class?EngeeTimer?
{

????private?int?minutes;

????private?Timer?timer?=?new?Timer();


????public?int?getMinutes()?
{
????????return?minutes;
????}


????public?void?setMinutes(int?minutes)?
{
????????this.minutes?=?minutes;
????}


????public?void?start()?
{


????????timer.schedule(new?TimerTask()?
{


????????????public?void?run()?
{
????????????????System.out.print("接受郵件");

????????????}

????????},?0,?minutes?*?1000?*?60);

????}


????public?Timer?getTimer()?
{
????????return?timer;
????}


????public?void?setTimer(Timer?timer)?
{
????????this.timer?=?timer;
????}

}

使用這幾行代碼之后,Timer本身會每隔5分鐘調用一遍server.checkNewMail()方法,不需要自己啟動線程。Timer本身也是多線程同步的,多個線程可以共用一個Timer,不需要外部的同步代碼。
在《The JavaTutorial》中有更完整的例子:
運行結果:
3分鐘后
hahaha,this is a timenrhahaha,this is a timenrhahaha,this is a timenrhahaha,this is a timenrhahaha,th


























































使用這幾行代碼之后,Timer本身會每隔5分鐘調用一遍server.checkNewMail()方法,不需要自己啟動線程。Timer本身也是多線程同步的,多個線程可以共用一個Timer,不需要外部的同步代碼。
在《The JavaTutorial》中有更完整的例子:
?1
package?test.Timer;
?2
?3
public?class?Main?
{
?4
?5
????
?6
????public?static?void?main(String[]?args)?
{
?7
????????EngeeTimer?entimer=new?EngeeTimer();
?8
????????entimer.setMinutes(1);
?9
????????entimer.start();
10
11
????}
12
13
}
14

?2

?3



?4

?5

?6



?7

?8

?9

10

11

12

13

14

運行結果:
3分鐘后
hahaha,this is a timenrhahaha,this is a timenrhahaha,this is a timenrhahaha,this is a timenrhahaha,th