计时器取消方法



我有一个关于类java.util.Timer的问题,特别是它的cancel()方法。

如果我写这样的代码并调用它4000次(例如),它不会停止执行,我猜应该是:

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    private int id = ++TimerTest.counter;
    @Override
    public void run() {
        if(counter % 100 == 0)
            System.out.println("TimerTest #" + id + "nI'm doing task: " + task);
        if(counter == 4000 && canceled == true){
            System.out.println("Canceling...");
            timer.cancel();
        }
    }
}, 0);

但我可以将其更改为:,而不是上面的脚本

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    private int id = ++TimerTest.counter;
    @Override
    public void run() {
        if(counter % 100 == 0)
            System.out.println("TimerTest #" + id + "nI'm doing task: " + task);
        if(counter == 4000 && canceled == true){
            System.out.println("Canceling...");
        }
    }
}, 0);
timer.cancel();

我在寻找相同的问题描述,但没有遇到任何特别的问题:)

问题似乎在于您似乎调用了计时器4000次。相反,你应该有1个定时器,并用它安排一段时间

public void schedule(TimerTask task, long delay, long period)

方法而非

public void schedule(TimerTask task, long delay)

下面是一个正确使用的例子:

import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
    private static int counter = 0;
    private void doTimer() throws InterruptedException {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                counter ++;
                System.out.println("TimerTest #" + counter + " I'm doing task");    
            }
        }, 0,1000);
        //Sleep for 10 seconds before cancelling the timer
        Thread.currentThread().sleep(10000);
        System.out.println("Timer cancelled");
        timer.cancel();
    }
    public static void main(String args[]) throws InterruptedException {
        new TimerTest().doTimer();
    }
}

这会在10秒后停止计时器:

TimerTest #1 I'm doing task
TimerTest #2 I'm doing task
TimerTest #3 I'm doing task
TimerTest #4 I'm doing task
TimerTest #5 I'm doing task
TimerTest #6 I'm doing task
TimerTest #7 I'm doing task
TimerTest #8 I'm doing task
TimerTest #9 I'm doing task
TimerTest #10 I'm doing task
Timer cancelled

最新更新