JavaFx platform.runlater 반환값, 작업 반환 대기

3649 단어 Javafx
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
    }
}

좋은 웹페이지 즐겨찾기