gpt4 book ai didi

java - 如何取消已经安排好的TimerTask?

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

我有一个小问题,我似乎无法正确处理。我在java中有以下类:

package pooledtcpconnector.utilities;

import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;

public final class Notifier implements Runnable {

private final ILogger logger;

private Timer mTimer;
private final int Treshold;
private final InputStream ResponseStream;
private final TimerTask DoWaitTask;

public Notifier(final InputStream _ResponseStream, final Integer _Treshold, final ILogger logger) {
this.logger = logger;

mTimer = new Timer();

this.ResponseStream = _ResponseStream;
this.Treshold = _Treshold;

DoWaitTask = new TimerTask() {
@Override
public void run() {
try {
int mSize = ResponseStream.available();
if (mSize >= Treshold) {
mTimer.cancel();
}
} catch (final IOException ex) {
final String ExceptionMessage = ex.getMessage();
logger.LogMessage(
this.getClass().getCanonicalName(),
"Notifier.DoWaitTask:run.ResponseStream.available",
ex.getClass().getCanonicalName(),
new String[]{
ExceptionMessage,
"Parameters:",
String.format("-"),
});

Logger.getLogger(Notifier.class.getCanonicalName()).log(Level.FINE, ex.getMessage(), ex.getCause());
}
}
};
}

@Override
public void run() {
synchronized (this) {
mTimer.scheduleAtFixedRate(DoWaitTask, 250, 200);
// Notification mechanism
notify();
}
}

}

此类将确保我们的应用程序不会开始处理 SocketInputStream,除非可用方法至少返回 Treshold。然而问题是,一旦我用计时器安排 DoWaitTask,它就会永远运行。通过取消计时器,任务仍然运行并且整个应用程序挂起,但更重要的是,一旦流已经被处理并关闭,它就会尝试调用流上的 available 。当然,这会导致一个很好的 IOException:流已关闭。

如何将计划任务与计时器一起停止? timer.cancel 显然是不够的。

问候, 乔伊

最佳答案

使用TimerTask.cancel()从计时器任务的 run() 方法中。根据此方法的 Javadoc:

Note that calling this method from within the run method of a repeating timer task absolutely guarantees that the timer task will not run again.

关于java - 如何取消已经安排好的TimerTask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25789822/

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