【发布时间】:2020-01-12 23:33:27
【问题描述】:
假设我有这个臃肿的例子。 我期望发生的是在控制台中获得几个数字大约 3 次,然后我期望打印“任务已停止”行,然后我就不会再得到数字了。
所以我想停止执行任务。到目前为止,我已经尝试cancel(true) 未来,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");
【问题讨论】:
标签: java concurrency scheduled-tasks