首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >JavaFX,Platform.runlater()有回调吗?

JavaFX,Platform.runlater()有回调吗?
EN

Stack Overflow用户
提问于 2016-09-23 13:36:18
回答 1查看 1.2K关注 0票数 2

我的应用程序通过调用Platform.runlater方法在FX线程上添加了多个Runnable,然后,我只想在FX平台队列中没有额外的Runnable时进行一些计算。但是我不知道正确的方式,有什么事件或回调机制来获取正确的时间吗?

目前,我强制应用程序线程随机休眠毫秒。

EN

回答 1

Stack Overflow用户

发布于 2016-09-23 17:41:31

这从一开始就不是一个好主意,因为您不知道其他代码使用Platform.runLater的是什么。此外,您不应该依赖这样的实现细节;就您所知,队列永远不会为空。

但是,您可以使用一个自定义类来发布这些Runnable,该类跟踪Runnable的数量,并在所有操作完成时通知您:

代码语言:javascript
运行
复制
public class UpdateHandler {
     private final AtomicInteger count;
     private final Runnable completionHandler;

     public UpdateHandler(Runnable completionHandler, Runnable... initialTasks) {
         if (completionHandler == null || Stream.of(initialTasks).anyMatch(Objects::isNull)) {
             throw new IllegalArgumentException();
         }
         count = new AtomicInteger(initialTasks.length);
         this.completionHandler = completionHandler;
         for (Runnable r : initialTasks) {
             startTask(r);
         }
     }

     private void startTask(Runnable runnable) {
         Platform.runLater(() -> {
             runnable.run();
             if (count.decrementAndGet() == 0) {
                 completionHandler.run();
             }
         });
     }

     public void Runnable runLater(Runnable runnable) {
         if (runnable == null) {
             throw new IllegalArgumentException();
         }
         count.incrementAndGet();
         startTask(runnable);
     }

}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39653295

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档