java有没有办法将ScheduledExecutorService与ExecutorCompletionService一起使用?
我正在尝试同时使用ExecutorCompletionService和ScheduledExecutorService
我需要做的是安排不同的活动,每个活动都有“执行前的延迟”,然后根据上一次运行的结果“重新安排它们”(不同的延迟)。"
我的问题是,我不能使用ExcecutorCompletionService“延迟”提交
我尝试了以下方法,但它会永远阻止
显然,我忽略了Java语言中的一个基本问题
是否仍然可以将任务调度到ScheduledExecutorService,以便CompletionService“了解它”
public class Bar {
private ScheduledExecutorService scheduledExecutor;
private Future<Status> action1Future;
private Future<Status> action2Future;
private ExecutorCompletionService<Status> pool;
private long delay1 = 10;
private long delay2 = 20;
private long delay3 = 30;
public void start() {
scheduledExecutor = Executors.newScheduledThreadPool(3);
Action1 a1 = new ActionOne(); // Action1 implements Callable<Status>
Action2 a2 = new ActionTwo(); // Action2 implements Callable<Status>
pool = new ExecutorCompletionService<Status>(scheduledExecutor);
action1Future = scheduledExecutor.schedule(a1, delay1, TimeUnit.SECONDS);
action2Future = scheduledExecutor.schedule(a2, delay1, TimeUnit.SECONDS);
monitorAndRestart();
}
private void monitorAndRestart() {
boolean isDone=false;
do {
try {
// THIS IS WHERE IT BLOCKS.
Future<Status> processedItem = pool.get();
if (processedItem == action1Future) {
if (processedItem.get() == Status.GOOD) {
action1Future = scheduledExecutor.schedule(new ActionOne(), delay1, TimeUnit.SECONDS);
} else {
action1Future = scheduledExecutor.schedule(new ActionOne(), delay2, TimeUnit.SECONDS);
}
} else if (processedItem == action2Future) {
if (processedItem.get() == Status.GOOD) {
action1Future = scheduledExecutor.schedule(new ActionOne(), delay2, TimeUnit.SECONDS);
} else {
action1Future = scheduledExecutor.schedule(new ActionOne(), delay3, TimeUnit.SECONDS);
}
}
} catch (InterruptedException e) {
isDone = true;
// handle this.. shudown whatever
}
catch (ExecutionException e) {
// handle this
}
} while (isDone == false);
}
public static void main(String[] args) {
Bar myRunner = new Bar();
myRunner.start();
}
}
如果我把“延迟放在可调用项中”,通过新的ActionOne(延迟)创建可调用项;并使用CompletionService。提交(…)它起作用了
actionFuture1 = pool.submit(new ActionOne(delay1));
/////
public class ActionOne implements Callable<Status>(
private final delay;
public ActionOne(long dl) {
delay=dl;
}
Status call() {
try {
Thread.sleep(delay * 1000); // seconds
return doSomething()
} catch (...) { //thread.sleep execptions}
}
}
所以我猜最后一个问题是:ScheduledExecutorService是否有比线程更好的本质。睡眠(延迟)怎么做
共 (0) 个答案