国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

使用java.util.Timer

2019-11-18 15:13:51
字體:
來源:轉載
供稿:網友

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

PRivate java.util.Timer timer; timer = new Timer(true); timer.schedule(new java.util.TimerTask() { public void run() { //server.checkNewMail(); 檢查新郵件 } }, 0, 5*60*1000);

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

public class AnnoyingBeep { Toolkit toolkit; Timer timer; public AnnoyingBeep() { toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new RemindTask(), 0, //initial delay 1*1000); //subsequent rate } class RemindTask extends TimerTask { int numWarningBeeps = 3; public void run() { if (numWarningBeeps > 0) { toolkit.beep(); System.out.println("Beep!"); numWarningBeeps--; } else { toolkit.beep(); System.out.println("Time´s up!"); //timer.cancel(); //Not necessary because we call System.exit System.exit(0); //Stops the AWT thread (and everything else) } } } ...}
這段程序,每隔3秒響鈴一聲,并打印出一行消息。循環3次。程序輸出如下:
Task scheduled.
Beep!
Beep! //one second after the first beep
Beep! //one second after the second beep
Time´s up! //one second after the third beep

Timer類也可以方便地用來作為延遲執行,比如下面的代碼延遲指定的時間(以秒為單位)執行某操作。類似電視的延遲關機功能。

...public class ReminderBeep { ... public ReminderBeep(int seconds) { toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.println("Time´s up!"); toolkit.beep(); //timer.cancel(); //Not necessary because we call System.exit System.exit(0); //Stops the AWT thread (and everything else) } } ...}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 台州市| 富宁县| 青铜峡市| 铜川市| 库车县| 延寿县| 渭南市| 平陆县| 广灵县| 河间市| 桐城市| 德化县| 伊春市| 定远县| 华池县| 渭源县| 临邑县| 明星| 定安县| 台东县| 浦北县| 芜湖县| 洛扎县| 嘉善县| 永靖县| 专栏| 陵水| 华安县| 麦盖提县| 晋州市| 宣武区| 长治市| 留坝县| 诏安县| 读书| 罗平县| 临潭县| 白城市| 禄丰县| 孟津县| 同德县|