【问题标题】:Thread is not terminated using conditional TimerTask线程未使用条件 TimerTask 终止
【发布时间】:2016-01-13 10:27:07
【问题描述】:

我根据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");
    }
}

【问题讨论】:

  • 它会永远运行吗?还是只有一次?
  • 它永远运行 Thilo。

标签: java multithreading timer


【解决方案1】:

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

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

【讨论】:

  • 啊,我明白了,我很傻。非常感谢您的及时回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多