java - 延迟一段时间后执行任务,如果遇到无限循环则停止
解决方案
java.util.concurrent.ScheduledFuture 可以帮助你但是更好地使用无限循环(如果可以的话)使用 while(!Thread.currentThread().isInterrupted())。这可以帮助你停止你的任务。
例子:
final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
final ScheduledFuture<?> schedule = scheduledExecutorService.schedule(() -> {
while(!Thread.currentThread().isInterrupted()) {
System.out.println("Hello world");
}
}, 5, TimeUnit.SECONDS);
Thread.sleep(10000);
schedule.cancel(true);
System.out.println("Stopped");
Thread.sleep(3000);
scheduledExecutorService.shutdown();