假设我有这个臃肿的例子。 我期望发生的情况是在控制台中获得几个数字大约三倍,然后我期望打印“任务已停止”行,然后我不会再获得任何数字。
所以我想停止执行任务。到目前为止,我已经尝试cancel(true)
future ,executor.shutdownNow)(
和executor.shutdown()
执行器,但是这些都不会导致我上面描述的行为。我错过了什么吗?有办法取消这个任务吗?
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.setRemoveOnCancelPolicy(true);
final int rareNumber = 302330233;
ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
int x = 0;
while (true) {
x++;
if(x % rareNumber == 0) {
System.out.println(x);
}
}
}, 1, 2, TimeUnit.SECONDS);
Thread.sleep(3_000);
// I'd like to stop a task here.
System.out.println("The task is stopped");
最佳答案
正确的方法是executor.shutdownNow()
。这会导致线程被中断。
但是您的线程当时没有等待/hibernate ,因此您不会收到 IterruptedException
因此您需要检查 Thread.intrrupted()
标志:
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.setRemoveOnCancelPolicy(true);
final int rareNumber = 302330233;
ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
int x = 0;
while (true) {
x++;
if(x % rareNumber == 0) {
System.out.println(x);
}
if (Thread.interrupted()) {
return;
}
}
}, 1, 2, TimeUnit.SECONDS);
Thread.sleep(3_000);
executor.shutdownNow();
// I'd like to stop a task here.
System.out.println("The task is stopped");
关于java - 停止 ScheduledThreadPoolExecutor Java 中的 sheduleAtFixedRate 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57883843/