【问题标题】:How to catch the task exception in java fx application?如何在 java fx 应用程序中捕获任务异常?
【发布时间】:2016-10-28 07:23:46
【问题描述】:
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javafx.concurrent.Task;


public class T {

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Task t = new Task(){

            @Override
            protected Object call() throws Exception {
                System.out.println(1/0);
                return null;
            }

        };

        //My progresss Bar in JavaFX
        //Progressbar.progressProperty().bind(t.progressProperty());

        Future future = executorService.submit(t);

        try {
            future.get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  //returns null if the task has finished correctly.

        executorService.shutdown();


}
}

我有一个类似于这样的代码我的代码任务在对象调用中有内部方法调用,它会引发 sql 异常,但我永远无法在 Executor 服务中捕获它,也只是在提交调用上方我有一个 javafx 的进度条但是那个使用 future 时,似乎也像主 ui 挂起一样卡住了。没有未来,进度条可以工作。

【问题讨论】:

    标签: java multithreading javafx executorservice


    【解决方案1】:

    Future.get 是一个阻塞调用。这就是 UI 挂起的原因。

    不要使用Future 来获取结果。而是使用TaskonSucceeded 事件处理程序。 onFailed 事件处理程序可用于获取异常。示例:

    t.setOnSucceeded(evt -> System.out.println(t.getValue()));
    t.setOnFailed(evt -> {
        System.err.println("The task failed with the following exception:");
        t.getException().printStackTrace(System.err);
    });
    executorService.submit(t);
    

    顺便说一句:这两个处理程序都在 JavaFX 应用程序线程上运行,因此可以安全地用于修改 UI 以向用户显示结果/错误。

    【讨论】:

      猜你喜欢
      • 2020-11-28
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 2014-04-23
      • 2011-10-13
      • 2016-12-07
      相关资源
      最近更新 更多