【问题标题】:Java FX Platform.runLater(() -> equivalent for long running TasksJava FX Platform.runLater(() -> 等效于长时间运行的任务
【发布时间】:2017-06-29 05:39:13
【问题描述】:

我了解到在 JavaFX 中相当于

SwingUtilities.invokeLater(new Runnable() {
  public void run() {
   dosomething();
 }
});

可能只是

Platform.runLater(() ->{ dosomething()};

对于一项长期运行的任务,我了解到您需要使用以下任务来包装事物:

Task<Void> task = new Task<Void>() {
  @Override
  public Void call() {
    dosomething();
  }
};
new Thread(task).start();

现在如果能有类似的 lambda 快捷方式,那就太好了

TaskLaunch.start(() -> dosomething());

我找到了

围绕这个讨论一些问题并尝试:

package com.bitplan.task.util;    
import java.util.concurrent.Callable;
import javafx.concurrent.Task;

/**
 * this is a utility task to launch tasks with lambda expressions
 * 
 * @author wf
 *
 */
public class TaskLaunch {
  /**
   * 
   * @param callable
   * @return the new task
   */
  public static <T> Task<T> task(Callable<T> callable) {
    Task<T> task = new Task<T>() {
      @Override
      public T call() throws Exception {
        return callable.call();
      }
    };
    return task;
  }
}

使用 JUnit 测试:

  Integer counter=0;
  boolean running=false;
  public Integer increment() {
    running=true;
    while (running) {
      counter++;
      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
      }
    }
    return counter;
  }
  /**
   * @throws Exception 
   */
  @Test
  public void testTaskLaunch() throws Exception {
    // https://stackoverflow.com/questions/30089593/java-fx-lambda-for-task-interface
    Task<Integer> task=TaskLaunch.task(() -> increment());
    try {
      Thread.sleep(20);
    } catch (InterruptedException e) {
      //
    }
    running=false;
    assertTrue(task.get()>10);
  }

这还不是我想看到的。问题似乎是 lambda 表达式在同一个线程中运行,而

new Thread(task).start();

部分需要整合。

需要什么才能获得(至少接近)上面提到的短线?

是一个

TaskLaunch.start(() -> dosomething());

可行吗?

基于@Damianos 提案https://stackoverflow.com/a/44817217/1497139

我试过了:

package com.bitplan.task;

import java.util.concurrent.Callable;

import javafx.concurrent.Task;

/**
 * this is a utility task to launch tasks with lambda expressions
 * 
 * @author wf
 *
 */
public class TaskLaunch<T> {

  Thread thread;
  Task<T> task;
  Callable<T> callable;
  Throwable throwable;
  Class<T> clazz;

  public Thread getThread() {
    return thread;
  }

  public void setThread(Thread thread) {
    this.thread = thread;
  }

  public Task<T> getTask() {
    return task;
  }

  public void setTask(Task<T> task) {
    this.task = task;
  }

  public Callable<T> getCallable() {
    return callable;
  }

  public void setCallable(Callable<T> callable) {
    this.callable = callable;
  }

  public Throwable getThrowable() {
    return throwable;
  }

  public void setThrowable(Throwable throwable) {
    this.throwable = throwable;
  }

  public Class<T> getClazz() {
    return clazz;
  }

  public void setClazz(Class<T> clazz) {
    this.clazz = clazz;
  }

  /**
   * construct me from a callable
   * 
   * @param callable
   */
  public TaskLaunch(Callable<T> callable, Class<T> clazz) {
    this.callable = callable;
    this.task = task(callable);
    this.clazz = clazz;
  }

  /**
   * 
   * @param callable
   * @return the new task
   */
  public static <T> Task<T> task(Callable<T> callable) {
    Task<T> task = new Task<T>() {
      @Override
      public T call() throws Exception {
        return callable.call();
      }
    };
    return task;
  }

  /**
   * start
   */
  public void start() {
    thread = new Thread(task);
    thread.start();
  }

  /**
   * start the given callable
   * @param callable
   * @param clazz - the return Type class
   * @return - the launch result
   */
  @SuppressWarnings({ "unchecked", "rawtypes" })
  public static TaskLaunch start(Callable<?> callable, Class<?> clazz) {
    TaskLaunch<?> launch = new TaskLaunch(callable, clazz);
    launch.start();
    return launch;
  }

}

并将测试更改为:

  /**
   * @throws Exception 
   */
  @SuppressWarnings("unchecked")
  @Test
  public void testTaskLaunch() throws Exception {
    // https://stackoverflow.com/questions/30089593/java-fx-lambda-for-task-interface
    TaskLaunch<Integer> launch = TaskLaunch.start(()->increment(),Integer.class);
    try {
      Thread.sleep(20);
    } catch (InterruptedException e) {
      //
    }
    running=false;
    assertTrue(launch.getTask().get()>10);
  }

这与我的目标很接近,但我得到了:

java.lang.IllegalStateException: Toolkit not initialized
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:273)
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:268)
at javafx.application.Platform.runLater(Platform.java:83)
at javafx.concurrent.Task.runLater(Task.java:1225)
at javafx.concurrent.Task$TaskCallable.call(Task.java:1417)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:745)

至少 TaskLaunch 现在包装:

  1. 线程
  2. 任务
  3. 可调用
  4. 潜在的异常/可抛出
  5. 任务结果的运行时类

这 5 项中的一些可能是多余的,并且可以从标准 Java 概念中获得。我认为至少在从一个班轮运行后快速访问这些内容很方便。

希望这可以正常工作并感谢您的帮助!

【问题讨论】:

  • Platform.runLater 用于从非 GUI 线程更新 GUI,一旦 GUI 线程空闲,它就会负责更新 GUI,因为任务用于非数据密集型任务与 GUI 相关,您希望它们在后台运行,这样它就不会冻结应用程序

标签: java multithreading javafx lambda


【解决方案1】:

new Thread(() -&gt; dosomething()).start() 应该可以解决问题

【讨论】:

  • 感谢您的提示。一条线现在正在工作 - 请在我自己的答案中查看解决方法。
【解决方案2】:

这是一种传统的XY problem

Task 不仅仅是一个后台线程,因此您可以使用常规线程。这是属性的美丽!

使用Task 的真正好处是可以安全地观察所有状态更改和进度更新并将其绑定到实时场景,同时在不同线程上执行所有后台工作。做繁重的工作是班级的工作并致电Platform.runLater

您需要 子类 而不是可运行对象的原因是,您可以调用其受保护的 updateXxx() 方法,而不必担心线程问题。

话虽如此,如果这是单行代码,您将没有任何好处。为此,请使用简单的线程。

希望这会有所帮助。

【讨论】:

  • 我的动机是“语法糖”。如果它可以用一个简短的衬里来表达,并且可以隐藏细节,那就太好了。我认为它也是对信息隐藏的一个很好的利用,如果代码更改很小,它会使决定长期运行/短期运行的任务更容易实现。
  • 您可以轻松使用@Damiano 的解决方案。否则,你不能。如前所述,这试图解决问题 X 并发明问题 Y。
【解决方案3】:

这样做会导致您无法将内容更新回 Task 类原生支持的 UI 线程。另一方面,如果你想在后台以“做和忘记”的方式做某事,我同意这会很有用。

问题就像你说的那样 - 你没有添加new Thead()Thread.start()。这样做:

public static void runInBackground(Runnable runnable) {
    Task<Void> task = new Task<>() {
        @Override
        public Void call() throws Exception {
            runnable.run();
            return null;
        }
    };
    new Thead(task).start();
}

runInBackground(() -> System.out.println(Thread.currentThread().hashCode()));

请注意,您的Task 不能再是非无效的,因为它现在不能返回任何东西。您的 lambda 需要能够引用 Task 对象以异步返回结果 - 这是使用 lambda 永远不可能实现的。

【讨论】:

  • 我对概述的包装方法很满意。我可以生火,可能会忘记。
【解决方案4】:

现在答案在基于 Damianos 提示的问题中。

我发现的异常的解决方法是

com.sun.javafx.application.PlatformImpl.startup(() -> {
});

但似乎有点 hacky ...

【讨论】:

    猜你喜欢
    • 2012-01-19
    • 2012-08-13
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 1970-01-01
    • 2013-07-08
    • 2014-09-10
    相关资源
    最近更新 更多