gpt4 book ai didi

JavaFX:可以从非 UI 线程安全地操纵节点的转换吗?

转载 作者:行者123 更新时间:2023-12-02 01:10:37 26 4
gpt4 key购买 nike

我一直在使用 javafx 开发机器人模拟器。它使用单独的线程来计算每次增量后机器人及其每个部件应位于的位置。 UI 的实际更新是通过调用 Platform.runLater() 来处理的。

以下是如何操作名为 leftFinger 的节点(在本例中为矩形)的示例:

首先,在 Controller 类中,创建一个 Translate 对象并将其添加到节点的变换中:

leftFingerTranslateTransform = new Translate(0, 0);
leftFinger.getTransforms().add(leftFingerTranslateTransform);

然后,在传入 Platform.runLater() 的方法中执行以下操作:

leftFingerTranslateTransform.setY(-40.0 * (armScale - 1.0));
leftFingerTranslateTransform.setX(fingerPos);

以上效果很好。

有一次,我不小心将一些节点重新定位代码(即对 Tranlate.setX()Translate.setY() 的调用)放入由非 UI 线程调用的方法中,而不调用 Platform.runLater() 。令我惊讶的是,这很有效,没有任何问题。但我想知道这是否会导致问题。

我对有关 javafx 和多线程的信息的搜索使我相信 UI 不能(或者至少不应该)直接从非 UI 线程进行操作。通过实验,我发现尝试从非 UI 线程向场景添加节点会导致引发异常,但操作属于节点的变换(即更改其属性)则不会。

我的问题是:属于节点的转换是否可以安全从非 UI 线程更改其属性(不使用 Platform.runLater() )?

最佳答案

当节点附加到 Activity 场景时,从非 UI 线程更改节点上的转换可能会导致竞争条件等问题。

不要这样做。

说明

来自维基百科race conditions :

Race conditions arise in software when an application depends on the sequence or timing of processes or threads for it to operate properly. As with electronics, there are critical race conditions that result in invalid execution and bugs. Critical race conditions often happen when the processes or threads depend on some shared state. Operations upon shared states are critical sections that must be mutually exclusive. Failure to obey this rule opens up the possibility of corrupting the shared state.

这里,共享状态是变换和从它们派生的内容的列表(例如场景的布局)。

来自Node Javadoc ,如评论中 Slaw 所链接:

Node objects may be constructed and modified on any thread as long they are not yet attached to a Scene in a Window that is showing. An application must attach nodes to such a Scene or modify them on the JavaFX Application Thread

它不安全的原因是 JavaFX UI 线程在定时脉冲上运行(请参阅 JavaFX architecture doc 以了解这一点),与任何非 UI 线程同时运行。在定时脉冲期间,将渲染场景、应用 CSS、应用变换、更新动画属性等。因此,如果您在 UI 线程在脉冲处理期间应用变换时修改非 UI 线程上的变换,你有一个潜在的竞争条件,这可能会导致共享状态损坏,并且结果是不可预测的,并且可能是非常不可取的。

关于JavaFX:可以从非 UI 线程安全地操纵节点的转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59446936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com