我有以下类,它安排每5分钟执行一次“更新”方法。事情是我想要“更新”执行固定次数。当我使用 scheduler.shutdown()时,更新方法不再执行,但程序仍在运行,我想什么都不做。
如何完全阻止它?
static Runnable update = new Runnable() {
@Override
public void run() {
if (count >= MAX_UPDATES) {
scheduler.shutdown();
} else {
//Do something
count++;
}
}
}
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(update, 0, 5, TimeUnit.MINUTES);
}
答案 0 :(得分:3)
我认为您可以使用shutdownNow方法,根据文档,这应该是Attempts to stop all actively executing tasks and halts the processing of waiting tasks
。
答案 1 :(得分:0)
您可以使用System.exit(int exitCode);
请注意,如果您这样做,jvm将立即终止。此外,这是唯一不会执行finally{}
块的情况。