【发布时间】:2019-04-04 23:25:58
【问题描述】:
我需要将一些工作负载拆分到线程并并行启动它们,因为它们是独立的。我还想用 JavaFx 在 ProgressBar 中显示整体进度。这意味着进度条显示到目前为止每个线程完成的总工作。
为简单起见,我们可以以这个Counter 类为例
public class Counter implements Runnable {
private int from, to;
public Counter(int from, int to) {
this.from = from;
this.to = to;
}
@Override
public void run() {
for (int i = from; i < to ; i++) {
// Do some heavy operation
// report about progress to the parent
}
// exit thread with status of success or failure
}
}
这个类将 from, to 作为边界条件。
为了不阻塞 UI,我使用了一个简单的 Task 类,像这样
public class MyTask extends Task<Integer> {
int iter;
public MyTask(int iter) {
this.iter = iter;
}
@Override
protected Integer call() throws Exception {
// Simply divide work load to each thread
int workers = 8;
int limit = iter/workers;
int rem = iter % workers;
// Creates a executor
ExecutorService executorService = Executors.newFixedThreadPool(workers);
for (int i = 0; i < workers; i++) {
int start = limit * i;
int end = limit * (i + 1);
if (i == workers - 1) end += rem;
Counter counter = new Counter(start, end);
executorService.submit(counter); // Submit work to be done
}
executorService.shutdown(); // start the execution
// Get their progress, update overall progress to UI
// Stop after all threads finished
}
}
在MyTask 中,我想按照 cmets 中的说明更新 UI 并整体完成。 (即每个线程完成的总计数)。
有什么方法可以做到这一点吗?聚合并行任务的进度并更新 UI 中的整体进度(我不计算已完成线程的数量,这是我要向 MyTask 报告的每个线程的当前进度)。
【问题讨论】:
-
这不使用
ProgessBar,但会更新Label。看看这个想法对你来说没问题。 stackoverflow.com/questions/51955550/… -
不是 100% 你要找的东西,但如果你没有找到其他东西:我已经实现了一个 ProgressMonitor 来监控工人列表:drombler.org/drombler-commons/0.13/docs/site/apidocs/org/…你可以单独取消每个工人。但是,它不提供聚合视图。
-
嗯,如果你能设法创建一个聚合的 Worker 并将它放在列表的第一位,ProgressMonitor 可能就是你要找的。span>
-
不知道这是否有帮助。 gist.github.com/jewelsea/4947946
标签: java multithreading user-interface javafx progress-bar