如何安全地确定节点是否属于另一个线程的场景

时间:2016-03-11 23:49:04

标签: multithreading javafx

JavaFX文档说,只要没有任何节点连接到场景,您就可以在JavaFX Thread之外自由构建节点层次结构。如果node连接到实际场景,则应该在JavaFX Application Thread内完成所有操作。

问题:是否可以确定给定节点是否属于场景。

如果不能在其他情况下立即执行操作 - 使用runLater方法。我想避免在没有必要的情况下经常在线程之间传递。

Node类具有getScene方法,当节点空闲时返回null。但它是否是线程安全的?

1 个答案:

答案 0 :(得分:2)

潜在(不良)答案

你可以使用Platform.runLater()安全地调用node.getScene(),然后按照Return result from javafx platform runlater中的定义返回结果,它会起作用,但我不认为我会建议非常频繁,因为对于并发应用程序来说这可能是一种非常低效的方法。

潜在的替代方法

以下是一个替代建议而非答案,并且它有可能不符合您的要求,但可能值得考虑答案。

我建议翻转你的逻辑。而不是:

  

如果给定节点属于场景。如果不能在其他情况下立即执行操作 - 使用runLater方法。

尝试:

  • 如果您在JavaFX应用程序线程上,请立即执行操作,否则,只需假设该项目已附加到活动场景并稍后通过runLater执行操作

这就是JavaFX内部其他并发项目(如任务)的工作原理。任务实现的一个例子是:

// If this method was called on the FX application thread, then we can
// just update the state directly and this will make sure that after
// the cancel method was called, the state will be set correctly
// (otherwise it would be indeterminate). However if the cancel method was
// called off the FX app thread, then we must use runLater, and the
// state flag will not be readable immediately after this call. However,
// that would be the case anyway since these properties are not thread-safe.
if (isFxApplicationThread()) {
    setState(State.CANCELLED);
} else {
    runLater(() -> setState(State.CANCELLED));
}

. . .

// This method exists for the sake of testing, so I can subclass and override
// this method in the test and not actually use Platform.isFxApplicationThread.
boolean isFxApplicationThread() {
    return Platform.isFxApplicationThread();
}
相关问题