【问题标题】:Call task's updateProgress调用任务的 updateProgress
【发布时间】:2014-05-16 17:51:05
【问题描述】:

我正在阅读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) ?

【问题讨论】:

    标签: java concurrency javafx javafx-2 task


    【解决方案1】:

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

    为了保持你的解耦,只需在DoSomething 中定义一个代表进度的DoubleProperty,并从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();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-05
      • 2011-12-14
      • 2011-03-20
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多