从不同线程同步请求 JavaFX 线程内的数据

Synchronously request data within JavaFX thread from different thread

我有一个单独的线程需要请求一些数据,这些数据可能同时在 JavaFX 线程中发生变化。我想在这个单独的线程中执行阻塞调用,以确保请求进入 JavaFX 线程。

Swing-GUI 测试框架 AssertJ 为此提供了易于使用的 API:

List list = GuiActionRunner.execute(new GuiQuery<...>...);

调用阻塞当前线程,在事件调度线程中执行传递的代码和returns所需的数据。

如何在 JavaFX 应用程序的生产代码中实现这一点?对于此要求,推荐的方法是什么?

好的,我想我现在明白了。你需要自己实现这样的东西:

AtomicReference<List<?>> r = new AtomicReference<>();
CountDownLatch l = new CountDownLatch(1);
Platform.runLater( () -> {
    // access data
    r.set(...)
    l.countDown();
})
l.await();
System.err.println(r.get());

这是一个替代解决方案,使用 FutureTask。这避免了在 AtomicReference 中显式锁存和管理同步数据。此处的代码可能足够简单,以至于在 Platform 中包含此功能是多余的。

FutureTask<List<?>> task = new FutureTask<>( () -> {
    List<?> data = ... ; // access data 
    return data ;
});
Platform.runLater(task);
List<?> data = task.get();

如果您想 pause a background thread to await user input,此技巧非常有用。