定時器Timer如何終止運行的問題


  JAVA自帶了一個定時器,那就是Timer,要實現一個Timer的demo非常簡單:

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

class Task extends TimerTask{
    @Override
    public void run() {
        System.out.println("******程序執行******");
    }
}

public class TaskTest {
    public static void main(String[] args){
        Timer timer = new Timer();
        Task task = new Task() ;
        timer.schedule(task, 3000);    //這里的單位是毫秒
    }
}

 

  用Eclipse運行一下, 問題來了,明明程序已經執行結束,為何卻沒有自動關閉呢?

 

  本着學習的精神,百度了一下,發現問這個問題的還真不少。明明已經結束,卻為什么沒有自動終止程序,這是因為系統默認當Timer運行結束后,如果沒有手動終止,那么則只有當系統的垃圾收集被調用的時候才會對其進行回收終止。既然這樣,我們可以使用System.gc()來實現程序的手動終止:

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

class Task extends TimerTask{
    @Override
    public void run() {
        System.out.println("******程序執行******");
        System.gc();
    }
}

public class TaskTest {
    public static void main(String[] args){
        Timer timer = new Timer();
        Task task = new Task() ;
        timer.schedule(task, 3000);    //這里的單位是毫秒
    }
}

 

  運行一下,OK,程序運行結束的同時,也成功終止。

  但是Sytem.gc()在一個項目中是不能隨便調用的,我們做做小測試如此做無可厚非,但是在項目中如此寫,太不合實際了。

  那么我們可以考慮用Timer類自帶的cancel()方法,實現Timer的終止。

  來看一下API中對cancel()方法的描述:

 

public void cancel()
Terminates this timer(終結這個timer), discarding any currently scheduled tasks(拋棄所有當前正在執行的TimerTask). Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.
Note that calling this method from within the run method of a timer task that was invoked by this timer absolutely guarantees that the ongoing task execution is the last task execution that will ever be performed by this timer.

This method may be called repeatedly; the second and subsequent calls have no effect.

  那么我們來實現一下:

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

public class TaskTest {
    public static void main(String[] args) {
        Timer timer = new Timer();
        // 三秒后開始執行,每隔一秒執行一次
        timer.schedule(new Task(timer), 3 * 1000, 1000);
    }
}

class Task extends TimerTask {
    private Timer timer;

    public Task(Timer timer) {
        this.timer = timer;
    }

    int i = 1;

    @Override
    public void run() {
        System.out.println("******程序執行******");
        //當執行到第5秒,程序結束
        if (i++ == 5) {
            this.timer.cancel();
            System.out.println("#### 程序結束 ####");
        }
    }
}

 

  OK,成功結束程序。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM