调用任务的updateProgress

时间:2014-05-16 17:51:06

标签: java concurrency javafx javafx-2 task

我正在阅读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受到保护,workdone / totalwork都定义为 public final ReadOnlyDoubleProperty

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

1 个答案:

答案 0 :(得分:3)

即使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(...)更改时调用{<1}}:

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();
        }
    }
}