Java的ExecutorService的 - 监控任务完成/状态栏

问题描述 投票:1回答:1

所以我有一个ExecutorService的成功拦网和现在运行的线性。我的问题是,我想添加一个状态更新,我无法弄清楚如何让期货在一次解决一个项目。看来,到时候我的未来<>中的第一项准备所以是最后一次。我希望能找到一个地方,在那里我可以知道有多少我的任务已经ExecutorService的剩余/总让我可以计算出一个简单的百分比指标。请注意,我打算在我的回收执行人及不希望将其关闭。

ExecutorService updateService = Executors.newSingleThreadExecutor();
Callable<String> callHour = () -> {
  //doStuff, unaware of total number of hourCalls
  return "done";
};
private void startMe(int hours){
  List<Future<String>> futureHours;
  List<Callable<String>> hourCalls = new ArrayList<>(hours);
    for (int hour = 0; hour < hours; ++hour) {
      hourCalls.add(callHour); //queue list (not running yet)
    }
    try {
      //executes queue and blocks thread
      futureHours = updateService.invokeAll(hourCalls);
      futureHours.get(0).get();//performs blocking
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
java android future executorservice blocking
1个回答
2
投票

有在工作两件事情在这里。


首先,如果我们看一看the documentation of ExecutorService#invokeAll(...),我们看到它返回

[...]拿着自己的状态期货和结果当所有完整的列表。 [...]

(由我强调)

你最想改用Executor#submit(...)


其次,你有没有那个连接到futureHours.get(0)任务首先执行的保证。我会建议使用Future#isDone()一些额外的逻辑:

private void startMe(int hours) {
  [...]
  try {
    [...]
    ArrayList<Future<String>> futureHoursDone = new ArrayList<>();
    final int numTasks = futureHours.size();
    int done = 0;
    double percentageDone = 0.0d;
    while (futureHours.isEmpty() == false) {
      for (int index = 0; index < futureHours.size(); ++index) {
        Future<String> futureHour = futureHours.get(index);
        if (futureHour.isDone()) {
          futureHours.remove(index);
          futureHoursDone.add(futureHour);
          --index;
          ++done;
          percentageDone = done / (double) numTasks;
        }
      }
    }
  } catch (Exception e) {
    // TODO: don't forget to HCF (https://en.wikipedia.org/wiki/Halt_and_Catch_Fire) :)
    e.printStackTrace();
  }
}

(这是一个粗略的草图。为了使进度,即percentage,可见外,你将不得不作出它的一个属性,并通过访问,例如,一些吸气)

© www.soinside.com 2019 - 2024. All rights reserved.