【问题标题】:Pause ScheduledExecutorService暂停 ScheduledExecutorService
【发布时间】:2011-09-26 13:49:08
【问题描述】:

我正在使用ScheduledExecutorService 执行以固定速率调用服务的任务。服务可能会向任务返回一些数据。该任务将数据存储在队列中。其他一些线程慢慢从队列中挑选项目

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class EverlastingThread implements Runnable {

    private ScheduledExecutorService executorService;
    private int time;
    private TimeUnit timeUnit;
    private BlockingQueue<String> queue = new LinkedBlockingQueue<String>(500);

    public EverlastingThread(ScheduledExecutorService executorService, int time, TimeUnit timeUnit) {
        this.executorService = executorService;
        this.time = time;
        this.timeUnit = timeUnit;
    }

    public void run() {

        // call the service. if Service returns any data put it an the queue
        queue.add("task");
    }

    public void callService() throws Exception {
        // while queue has stuff dont exucute???????????

        executorService.scheduleAtFixedRate(this, 0, time, timeUnit);
    }
}

如何暂停 executorService,直到任务填充的队列被清除。

【问题讨论】:

    标签: java scheduled-tasks executor


    【解决方案1】:

    你可以的

    if(!queue.isEmpty()) return; 
    

    一开始。

    如果您正在使用具有队列的 ScheduledExecutorService,为什么要使用它来添加到另一个队列。不能只使用服务中的队列吗?

    【讨论】:

    • 感谢您的回答,我在开始时正在记录 queue.isEmpty() 并且它始终是正确的。请解释一下服务中关于队列的部分。
    • 如果您希望另一个线程执行任务,您可以拥有一个 ExecutorService 并将您想做的事情提交给它。在您那里的示例中,您可以在 run() 中执行第二个线程将执行的操作。
    【解决方案2】:

    当执行器关闭时,它不再接受新任务并等待当前任务终止。但是你不想终止你的执行者,只是暂停它。

    所以你可以做的是,在你的任务中你只处理一个空队列。因为你的任务只是不时执行,所以当没有处理要做的时候,它的 CPU 消耗将接近 0。这是“if(!queue.isEmpty()) 返回;”来自 Peter Lawrey 的回应。

    其次,您使用阻塞队列。这意味着如果您在队列为空时调用方法 take() 来获取队列中的元素,则执行线程将等待直到某个元素自动添加到队列中。

    所以:

    • 您不能暂停执行程序 这会使您的代码复杂化。
    • 阻塞队列完全是设计使然 你需要什么:阻止任务如果 队列是空的。
    • 如果您愿意,可以让 定期任务运行并检查是否 队列为空。
    • 您应该已经使用了一个或 无论如何在你的任务中的其他方式 否则你会有 NullPointerException 当队列 是空的。

    【讨论】:

    • 嗨,这只是代码的一部分。还有其他线程从队列中获取(),因此将等待上述部分将内容添加到队列中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多