我正在使用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,直到该任务填充的队列被清除。
发布于 2011-07-01 16:36:58
当一个执行器被关闭时,它不再接受新的任务,并等待当前的任务终止。但是你不想终止你的executor,那就暂停它吧。
因此,您可以做的是,在您的任务中,您只需处理一个空队列。因为您的任务只是时不时地执行,所以当没有处理时,它的CPU消耗将接近于0。这是来自Peter Lawrey response的"if(!queue.isEmpty()) return;“。
其次,您使用阻塞队列。这意味着,如果在队列为空时调用take()方法来获取队列中的元素,则executor线程将等待,直到某些元素被自动添加到队列中。
所以:
发布于 2011-07-01 16:13:33
你可以做到
if(!queue.isEmpty()) return; 在开始的时候。
如果您正在使用具有队列ScheduledExecutorService,为什么还要使用它来添加到另一个队列。你不能只在服务中使用队列吗?
https://stackoverflow.com/questions/6545204
复制相似问题