暂停ScheduledExecutorService

art*_*ved 9 java scheduled-tasks executor

我使用a 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Nic*_*uet 3

当执行器关闭时,它不再接受新任务并等待当前任务终止。但您不想终止执行程序,只需暂停它即可。

所以你能做的就是在你的任务中你只处理一个空队列。因为你的任务只是偶尔执行,所以当没有处理可做时,CPU 消耗将接近于 0。这是“if(!queue.isEmpty()) 返回;” 来自彼得·劳瑞的回应。

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

所以:

  • 您无法暂停执行程序,即使这会使您的代码变得复杂。
  • 阻塞队列的设计正是您所需要的:如果队列为空,则阻塞任务。
  • 如果您愿意,可以让定期任务运行并检查队列是否为空。
  • 无论如何,您应该在任务中使用其中一种或另一种方式,否则当队列为空时您将出现 NullPointerException。