java - 使用条件 TimerTask 不会终止线程

标签 java multithreading timer

我根据 this article 中的提醒示例测试了一个简单的 Timer 和 TimerTask .

唯一的区别是我在timer.cancel()之前使用条件if。在原始示例中,线程按预期停止,但在我的代码中,它不会停止。怎么了?

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

public class ConditionalReminder {
    Timer           timer;

    public ConditionalReminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
    }

    class RemindTask extends TimerTask {
        int counter;

        public void run() {
            counter++;
            System.out.format("Time's up!%n");
            if(counter==100) 
            {
                timer.cancel(); //should terminate thread
            }
        }
    }

    public static void main(String args[]) {
        new ConditionalReminder(2);
        System.out.format("Task scheduled.%n");
    }
}

最佳答案

Timer.schedule(TimerTask, long)安排任务在提供的延迟后执行一次。如果您希望重复,则需要使用 Timer.schedule(TimerTask, long, long) 。例如:

int delay = 0;
int interval = seconds * 1000;
timer.schedule(new RemindTask(), delay, interval);

关于java - 使用条件 TimerTask 不会终止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34757345/

相关文章:

java - 显示图像而不在 xml 中指定 src

java - Grails 是大型企业 Web 应用程序的可行选择吗?

java - MapReduce如何从输入文件读取来获取键和值

C++ 需要线程安全的经过良好测试的容器(非微软)

c++ - 具有 `k` 个线程的多线程程序的运行速度能否比其顺序版本快 `k` 倍以上?

timer - 如何从 Web 服务器重启(或代码刷新/升级)中恢复 Go 计时器?

c - 在c中打印更新变量

java - Android:聚焦 EditText 时不调用 onBackPressed

java - Thread 类如何在另一个类中调用?

c# - C# 中的高分辨率计时器