JavaFx platform.runlater 返回值, 等待任务返回

在 JavaFx 中,如果在非Fx线程要执行Fx线程相关的任务,必须在 Platform.runlater 中执行,
而 runlater 中代码将不会阻塞当前线程,所以当需要 runlater 中代码执行返回值,再顺序执行后续代码时,需要采用以下方法:

// 定义一个FutureTask,然后 Plateform.runLater() 这个futuretask
                        final FutureTask query = new FutureTask(new Callable() {
                            @Override
                            public String call() throws Exception {
                                    // 新建一个窗口(方法中将创建stage)
                                    VcodeController vc = new VcodeController();
                                    return vc.show(url4vcode);
                            }
                        });

                        Platform.runLater(query);       // 重点

                        String vcode = query.get();     // 这样就能获取返回值

                        System.out.println(vcode);

另外一种做法,利用 CountDownLatch

/**
 * Runs the specified {@link Runnable} on the
 * JavaFX application thread and waits for completion.
 *
 * @param action the {@link Runnable} to run
 * @throws NullPointerException if {@code action} is {@code null}
 */
public static void runAndWait(Runnable action) {
    if (action == null)
        throw new NullPointerException("action");

    // run synchronously on JavaFX thread
    if (Platform.isFxApplicationThread()) {
        action.run();
        return;
    }

    // queue on JavaFX thread and wait for completion
    final CountDownLatch doneLatch = new CountDownLatch(1);
    Platform.runLater(() -> {
        try {
            action.run();
        } finally {
            doneLatch.countDown();
        }
    });

    try {
        doneLatch.await();
    } catch (InterruptedException e) {
        // ignore exception
    }
}

你可能感兴趣的:(Javafx)