Java多線程基礎(二)定時器類:Timer類和TimerTask類

jopen 8年前發布 | 17K 次閱讀 Java開發

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/

來自: http://blog.csdn.net//kingzone_2008/article/details/45270171

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!