gpt4 book ai didi

java - 如何在 Java 中停止 TimerTask

转载 作者:行者123 更新时间:2023-12-01 11:33:25 26 4
gpt4 key购买 nike

我用Java实现了一个TimerTask,我需要在一段时间后停止线程:

        .... 
timer = new Timer(); // At this line a new Thread will be created

TimerTask timerTask = new TimerTask() {

int tweetCounter = 0;
String message;

@Override
public void run() {
try {
while ((message = reader.readLine()) != null && (tweetCounter < 100)) {
bucket.add(message);
tweetCounter++;

out.println("Number of messages: " + tweetCounter);
out.println("Nano Time: " + System.nanoTime());

}
} catch (IOException e) {
e.printStackTrace();
}
}
};
timer.schedule(timerTask, 30000);
......

此时我尝试:

    timerTask.cancel();
timer.cancel();
timer.purge();

此后什么也没有发生,程序也永远不会退出。如何停止 TimerTask 线程?

最佳答案

timer.cancel();
timer.purge();

会起作用的。

int java.util.Timer.purge()

Removes all canceled tasks from the task queue. If there are no other references on the tasks, then after this call they are free to be garbage collected.

Returns: the number of canceled tasks that were removed from the task queue.

关于java - 如何在 Java 中停止 TimerTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30235741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com