暂停 ScheduledExecutorService [英] Pause ScheduledExecutorService

查看:91
本文介绍了暂停 ScheduledExecutorService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using a ScheduledExecutorService to execute a task that calls a service at a fixed rate. The service may return some data to the task. The task stores data in a queue. Some other threads slowly pick items from the queue

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 直到任务填充的队列被清除.

How do I pause the executorService until the queue populated by the task has been cleared.

推荐答案

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

When an executor is shudown, it do no longer accept new task and wait for the current ones to terminate. But you don't want to terminate your executor, just pause it.

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

So what you can do, is that in your task you just deal with an empty queue. Because you task is only to be executed from time to time, CPU consumption will be near to 0 for it when there is no processing to do. this is the "if(!queue.isEmpty()) return;" from Peter Lawrey response.

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

Second, you use a blocking queue. That mean that if you call the method take() to get a queued element while the queue is empty, the executor thread will wait until some element is added to the queue automatically.

所以:

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

这篇关于暂停 ScheduledExecutorService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆