【问题标题】:Stop a thread ScheduledThreadPoolExecutor after some condition occure在某些情况发生后停止线程 ScheduledThreadPoolExecutor
【发布时间】:2020-05-05 17:21:29
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: java multithreading scheduled-tasks threadpool threadpoolexecutor


    【解决方案1】:

    您可以按一项安排任务,并在安排下一个任务之前检查您的状况:

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

    【讨论】:

    • 非常感谢!这似乎是我想要的。如果我错了,请纠正我,应该是'if(value == null)'对吗?另外,能否请您解释一下这一行 - 'executor.schedule(this, delay - (System.currentTimeMillis() - time), TimeUnit.MILLISECONDS);'?再次感谢!
    • 是的,应该是value==null。即使getSomeValue 运行缓慢,我们也使用delay - (System.currentTimeMillis() - time) 来保持固定延迟。如果我们只是使用delay,那么如果getSomeValue运行,例如25ms,那么它将在delay + 25 ms 中调用一次,而不是在delay ms 中调用一次。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    相关资源
    最近更新 更多