首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >暂停ScheduledExecutorService

暂停ScheduledExecutorService
EN

Stack Overflow用户
提问于 2011-07-01 16:00:45
回答 2查看 7.4K关注 0票数 9

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

代码语言:javascript
复制
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,直到该任务填充的队列被清除。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-07-01 16:36:58

当一个执行器被关闭时,它不再接受新的任务,并等待当前的任务终止。但是你不想终止你的executor,那就暂停它吧。

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

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

所以:

  • 您不能暂停执行器,即使这会使您的代码复杂化。
  • 阻塞队列的设计完全符合您的需要:如果队列为空,则阻塞任务。
  • 如果您愿意,可以让定期任务运行并检查队列是否为空。
  • 您无论如何都应该在任务中使用一种或另一种方法,否则当队列为空时,您将使用NullPointerException。
票数 3
EN

Stack Overflow用户

发布于 2011-07-01 16:13:33

你可以做到

代码语言:javascript
复制
if(!queue.isEmpty()) return; 

在开始的时候。

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6545204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档