首页 > 解决方案 > 在某些情况发生后停止线程 ScheduledThreadPoolExecutor

问题描述

我想要一些线程池,每隔固定时间运行一些任务(这个线程池一直在获取任务)。每个任务调用一些 API 来获取一些值,该值可以为 null。只有当返回值为空时,我才希望任务再次运行(在固定时间之后)。否则,我不希望此任务再次运行。有没有办法做到这一点?我唯一想到的是使用 ScheduledThreadPoolExecutor 并从内部杀死特定线程,但我没有找到这样做的方法,我不确定这是一个好习惯。

谢谢!

标签: javamultithreadingscheduled-tasksthreadpoolthreadpoolexecutor

解决方案


您可以安排一个任务并在安排下一个任务之前检查您的条件:

public class Solver {

    final long delay = 500L;

    String getSomeValue() {
        if (Math.random() < 0.8) return "not-null";
        return null;
    }

    void init() {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(8);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                long time = System.currentTimeMillis();
                String value = getSomeValue();
                System.out.println("" + value + " " + System.currentTimeMillis());
                if (value == null) {
                    executor.schedule(this, delay - (System.currentTimeMillis() - time), TimeUnit.MILLISECONDS);
                }
            }
        };
        executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
    }

    public static void main(String[] args) {
        new Solver().init();
    }

}

推荐阅读