首页 > 解决方案 > 延迟一段时间后执行任务,如果遇到无限循环则停止

问题描述

我想执行一个具有初始延迟的任务,并且如果它陷入无限循环,则能够停止它。

我检查了TimerTask,但这将在完成后取消 timerTask。我希望在完成之前停止正在运行的任务。

标签: javamultithreading

解决方案


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();

推荐阅读