如何从循环更新任务进度?

时间:2018-02-21 05:13:29

标签: java progress-bar task

我有Task运行几种方法来完成最终结果。我正在更新ProgressBar,但需要帮助找出如何确定准确反映这一进展所需的等式。

我的任务通过几个“步骤”直到完成。但是,其中一个步骤遍历ArrayList,我希望我的ProgressBar在每次迭代后更新,但在运行时之前我不知道List的大小。

例如,我希望此循环占整体进度的75%,但不是等待它完成然后调用updateProgress(75, 100),例如,我想更新{{1}在循环的每次迭代之后。

我只是不知道用什么方程式来完成这项工作。

ProgressBar的伪方法:

Task

1 个答案:

答案 0 :(得分:0)

假设总计100%,你的循环占75%

  • doThis() - > 8%
  • doThisToo() - > 8%
  • 循环 - > 75%
  • doThisLast() - >剩余9%

只需计算列表中一个项目所代表的百分比,并在处理完每个项目后按此金额更新: 此解决方案将stepPerThing计算为double,并添加到循环之前的stepValue,以避免截断/舍入错误。

protected void call()  throws Exception {

  int totalSteps = 100;
  int currentStep = 0;

  // Step one (fast)
  doThis();
  currentStep += 8;
  updateProgress(currentStep, totalSteps);

  // Step two (fast)
  doThisToo();
  currentStep += 8;
  updateProgress(currentStep, totalSteps);

  // Step three (iterates through an ArrayList)
  int nbThings = listOfThings.length;
  double stepPerThing = 75d / (double)nbThings;
  int stepBeforeLoop = currentStep;
  for(int i = 0; i<nbThings; i++) {
    Class clazz = listOfThings[i];
    // Do something with the list
    int step = stepBeforeLoop + (int)((i+1)*stepPerThing);
    updateProgress(step, totalSteps);
  }

  // Step four (fast)
  doThisLast();
  updateProgress(totalSteps, totalSteps);
}

假设有10个数组,它会:

8/100
16/100
-- Loop starts here
23/100
31/100
38/100
46/100
53/100
61/100
68/100
76/100
83/100
91/100
-- Loop ends here
100/100