Java多線程基礎(二)定時器類:Timer類和TimerTask類,timertimertask
Java多線程基礎(二)定時器類:Timer類和TimerTask類
Timer類和TimerTask類是jdk實現定時器功能的早期方法,jdk1.5以前就支援Timer類和TimerTask類。JDK1.5之後引入了新的機制,將在後續博文中研究。
1 指定時間間隔後執行任務
import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class TraditionalTimerTest { public static void main(String[] args) { // 啟動定時器線程,並在10000毫秒後執行TimerTask執行個體的run方法 new Timer().schedule(new TimerTask() { @Override public void run() { System.out.println("bombing!"); } }, 10000); while(true) { System.out.println("時鐘時間:" + new Date().getSeconds()); try { Thread.sleep(1000);// 主線程每隔1秒鐘,列印當前時鐘時間 } catch (InterruptedException e) { e.printStackTrace(); } } }}
調用的主要java API的原始碼及java doc:
public void schedule(TimerTask task, long delay) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); sched(task, System.currentTimeMillis()+delay, 0); }
Schedules the specified task for execution after the specified delay.
安排在指定延遲後執行指定的任務。
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
Throws:
IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
NullPointerException - if task is null
2 指定時間間隔後迴圈執行任務
import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class TraditionalTimerTest { public static void main(String[] args) { // 啟動定時器線程,並在10000毫秒後開始,每隔3000毫秒執行一次定時任務 new Timer().schedule(new TimerTask() {// 定時任務 @Override public void run() { System.out.println("bombing!"); } }, 10000, 3000); while(true) { System.out.println("時鐘時間:" + new Date().getSeconds()); try { Thread.sleep(1000);// 主線程每隔1秒鐘,列印當前時鐘時間 } catch (InterruptedException e) { e.printStackTrace(); } } }}
調用的主要java API的原始碼及java doc:
public void schedule(TimerTask task, long delay, long period) { if (delay < 0) throw new IllegalArgumentException("Negative delay."); if (period <= 0) throw new IllegalArgumentException("Non-positive period."); sched(task, System.currentTimeMillis()+delay, -period); }
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.
安排指定的任務從指定的延遲後開始進行重複的 固定順延強制。以近似固定的時間間隔(由指定的周期分隔)進行後續執行。
In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well. In the long run, the frequency of execution will generally be slightly lower than the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).
在固定順延強制中,根據前一次執行的實際執行時間來安排每次執行。如果由於任何原因(如記憶體回收或其他後台活動)而延遲了某次執行,則後續執行也將被延遲。從長期來看,執行的頻率一般要稍慢於指定周期的倒數(假定 Object.wait(long) 所依靠的系統時鐘是準確的)。
Fixed-delay execution is appropriate for recurring activities that require “smoothness.” In other words, it is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run. This includes most animation tasks, such as blinking a cursor at regular intervals. It also includes tasks wherein regular activity is performed in response to human input, such as automatically repeating a character as long as a key is held down.
固定順延強制適用於那些需要“平穩”啟動並執行重複活動。換句話說,它適用於在短期運行中保持頻率準確要比在長期運行中更為重要的活動。這包括大多數動畫任務,如以固定時間間隔閃爍的游標。這還包括為響應人機輸入所執行的固定活動,如在按住鍵時自動重複輸入字元。
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay < 0, or delay + System.currentTimeMillis() < 0, or period <= 0
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
NullPointerException - if task is null
3 更靈活地間隔
每隔2秒,4秒,2秒,4秒,…,迴圈執行任務。
方法1 定義一個TimerTask類
import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class TraditionalTimerTest { static int count = 0; public static void main(String[] args) { class MyTimerTask extends TimerTask { @Override public void run() { count = (count+1)%2;// 用於定製不同的間隔時間 System.out.println("bombing!"); new Timer().schedule( new MyTimerTask(),//遞迴地執行個體化新的定時任務 2000 + 2000 * count); } } new Timer().schedule(new MyTimerTask(), 2000); while(true) { System.out.println("時鐘時間:" + new Date().getSeconds()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }}
方法2 定義兩個/多個TimerTask類
import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class TraditionalTimerTest { public static void main(String[] args) { new Timer().schedule(new MyTimerTask1(), 2000); while(true) { System.out.println("時鐘時間:" + new Date().getSeconds()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }}class MyTimerTask1 extends TimerTask { @Override public void run() { System.out.println("Task1"); new Timer().schedule(new MyTimerTask2(), 2000);// 啟動定時任務2 }}class MyTimerTask2 extends TimerTask { @Override public void run() { System.out.println("Task2"); new Timer().schedule(new MyTimerTask1(), 4000);// 啟動定時任務1 }}
4 Timer的其他常用API
| 傳回值 |
方法簽名 |
| void |
schedule(TimerTask task, Date time)
Schedules the specified task for execution at the specified time.
安排在指定的時間執行指定的任務。如果此時間已過去,則安排立即執行該任務。 |
| void |
schedule(TimerTask task, Date firstTime, long period)
Schedules the specified task for repeated fixed-delay execution, beginning at the specified time.
安排指定的任務在指定的時間開始進行重複的 固定順延強制。以近似固定的時間間隔(由指定的周期分隔)進行後續執行。
在固定順延強制中,根據前一次執行的實際執行時間來安排每次執行。如果由於任何原因(如記憶體回收或其他後台活動)而延遲了某次執行,則後續執行也將被延遲。在長期運行中,執行的頻率一般要稍慢於指定周期的倒數(假定 Object.wait(long) 所依靠的系統時鐘是準確的)。
固定順延強制適用於那些需要“平穩”啟動並執行重複執行活動。換句話說,它適用於在短期運行中保持頻率準確要比在長期運行中更為重要的活動。這包括大多數動畫任務,如以固定時間間隔閃爍的游標。這還包括為響應人類活動所執行的固定活動,如在按住鍵時自動重複輸入字元。 |
| void |
schedule(TimerTask task, long delay)
Schedules the specified task for execution after the specified delay.
安排在指定延遲後執行指定的任務。 |
| void |
schedule(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay.
安排指定的任務從指定的延遲後開始進行重複的 固定順延強制。以近似固定的時間間隔(由指定的周期分隔)進行後續執行。
在固定順延強制中,根據前一次執行的實際執行時間來安排每次執行。如果由於任何原因(如記憶體回收或其他後台活動)而延遲了某次執行,則後續執行也將被延遲。從長期來看,執行的頻率一般要稍慢於指定周期的倒數(假定 Object.wait(long) 所依靠的系統時鐘是準確的)。
固定順延強制適用於那些需要“平穩”啟動並執行重複活動。換句話說,它適用於在短期運行中保持頻率準確要比在長期運行中更為重要的活動。這包括大多數動畫任務,如以固定時間間隔閃爍的游標。這還包括為響應人類活動所執行的固定活動,如在按住鍵時自動重複輸入字元。 |
| void |
scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.
安排指定的任務在指定的時間開始進行重複的 固定速率執行。以近似固定的時間間隔(由指定的周期分隔)進行後續執行。
在固定速率執行中,相對於已安排的初始執行時間來安排每次執行。如果由於任何原因(如記憶體回收或其他後台活動)而延遲了某次執行,則將快速連續地出現兩次或更多次執行,從而使後續執行能夠趕上來。從長遠來看,執行的頻率將正好是指定周期的倒數(假定 Object.wait(long) 所依靠的系統時鐘是準確的)。
固定速率執行適用於那些對絕對 時間敏感的重複執行活動,如每小時準點打鐘報時,或者在每天的特定時間運行已安排的維護活動。它還適用於那些完成固定次數執行的總計時間很重要的重複活動,如倒計時的計時器,每秒鐘滴答一次,共 10 秒鐘。最後,固定速率執行適用於安排多次重複執行的計時器任務,這些任務相互之間必須保持同步。 |
| void |
scheduleAtFixedRate(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.
安排指定的任務在指定的延遲後開始進行重複的 固定速率執行。以近似固定的時間間隔(由指定的周期分隔)進行後續執行。
在固定速率執行中,根據已安排的初始執行時間來安排每次執行。如果由於任何原因(如記憶體回收或其他後台活動)而延遲了某次執行,則將快速連續地出現兩次或更多的執行,從而使後續執行能夠“追趕上來”。從長遠來看,執行的頻率將正好是指定周期的倒數(假定 Object.wait(long) 所依靠的系統時鐘是準確的)。
固定速率執行適用於那些對絕對 時間敏感的重複執行活動,如每小時準點打鐘報時,或者在每天的特定時間運行已安排的維護活動。它還適用於那些完成固定次數執行的總計時間很重要的重複活動,如倒計時的計時器,每秒鐘滴答一次,共 10 秒鐘。最後,固定速率執行適用於安排多個重複執行的計時器任務,這些任務相互之間必須保持同步。 |
更多詳細API資訊可以參考Java SE API:
英文API:http://docs.oracle.com/javase/6/docs/api/index.html
中文API:http://tool.oschina.net/apidocs/apidoc?api=jdk-zh
更複雜的定時器可以使用quartz庫:http://www.quartz-scheduler.org/