gpt4 book ai didi

java - 调用任务的updateProgress

转载 作者:行者123 更新时间:2023-11-30 08:23:25 25 4
gpt4 key购买 nike

我正在阅读 class Task 的文档

    final Task<Void> task = new Task<Void>() {
@Override public Void call() {
for(int i=0;i<datesAndStudies.length;i++){
updateProgress(i,datesAndStudies.length);
DoSomething something = new DoSomething();
something.VeryLongAndTimeConsumingMethod(i);
}
return null;
}
};

我注意到 updateProgress 是 protected ,workdone/totalwork 都被定义为 public final ReadOnlyDoubleProperty

是否有一种方法/解决方法来更新/调用 updateProgress 或从方法编辑这些值(workdone/totalwork):类 DoSomething 中的 VeryLongAndTimeConsumingMethod(int i) ?

最佳答案

即使 updateProgress(...)是公开的,您必须传递对 Task 的引用给你的DoSomething类,它创建了一些非常丑陋的耦合。如果你的 Task 之间有那种程度的耦合实现和您的 DoSomething类,您也可以只在 Task 中定义耗时的方法子类本身,并摆脱其他类:

final Task<Void> task = new Task<Void>() {
@Override
public Void call() {
for (int i=0; i<datesAndStudies.length; i++) {
veryLongAndTimeConsumingMethod(i);
}
return null ;
}

private void veryLongAndTimeConsumingMethod(int i) {
// do whatever...
updateProgress(...);
}
};

为了保持解耦,只需定义一个 DoubleProperty代表进展 DoSomething ,并从 Task 观察它, 调用 updateProgress(...)当它改变时:

public class DoSomething {
private final ReadOnlyDoubleWrapper progress = new ReadOnlyDoubleWrapper(this, "progress");
public double getProgress() {
return progress.get();
}
public ReadOnlyDoubleProperty progressProperty() {
return progress.getReadOnlyProperty();
}
public void veryLongAndTimeConsumingMethod(int i) {
// ..
progress.set(...);
}
}

然后:

final Task<Void> task = new Task<>() {
@Override
public Void call() {
for (int i=0; i<datesAndStudies.length; i++) {
DoSomething something = new DoSomething();
something.progressProperty().addListener(
(obs, oldProgress, newProgress) -> updateProgress(...));
something.veryLongAndTimeConsumingMethod();
}
}
}

关于java - 调用任务的updateProgress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23701639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com