简体   繁体   English

JavaFX时间轴与ScheduledExecutorService

[英]JavaFX Timeline vs ScheduledExecutorService

In a JavaFX 8 project, you can use javafx.animation.Timeline like this: 在JavaFX 8项目中,可以像这样使用javafx.animation.Timeline:

Timeline timeline = new Timeline(
            new KeyFrame(Duration.millis(250),
                         actionEvent -> {
                               updateTemperature();
                         }
            )
    );
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();

Or you can something very similar using a ScheduledExecutorService : 或者,您可以使用ScheduledExecutorService类似的操作:

executorService.scheduleAtFixedRate(this::updateTemperature, 0, 250, TimeUnit.SECONDS);

Are there any "best practises" for using one over the other? 是否有任何一种“最佳实践”来代替另一种?

As with most UI toolkits, in JavaFX you must not access UI components that are part of the display from any thread other than the dedicated UI thread (the FX Application Thread in the case of JavaFX). 与大多数UI工具包一样,在JavaFX中,您不得从专用UI线程(对于JavaFX而言是FX Application Thread)以外的任何线程访问作为显示一部分的UI组件。 Additionally, code that takes (or may take) time to run (eg has blocking calls, as with I/O or networking) should not be executed on the UI thread as it will make the UI unresponsive. 另外,花费(或可能花费)时间运行的代码(例如,与I / O或网络一样具有阻塞调用)不应在UI线程上执行,因为它将使UI无响应。

The two code snippets you posted are quite different with regard to threading. 您发布的两个代码段在线程方面完全不同。 The ScheduledExecutor will execute updateTemperature() on a background thread (ie not the FX Application Thread). ScheduledExecutor将在后台线程(即不是FX Application线程)上执行updateTemperature() )。 This is appropriate if updateTemperature() takes a long time to run; 如果updateTemperature()需要很长时间才能运行,则这是适当的; but it will likely throw an exception (or, worse, have the potential of leaving the UI in an inconsistent state) if it accesses the UI. 但如果它访问UI,则可能会引发异常(或更糟糕的是,有可能使UI处于不一致状态)。

By contrast, the Timeline creates no new threads and executes updateTemperature() on the FX Application Thread. 相反, Timeline创建任何新线程,并在FX Application线程上执行updateTemperature() If updateTemperature() accesses the UI, it must be performed on this thread and this is a convenient way to do so. 如果updateTemperature()访问UI,则必须在此线程上执行,这是一种方便的方法。 If it takes a long time to run (which I assume it doesn't, since you're calling it 4 times per second), it will have the effect of making the UI unresponsive. 如果运行时间很长(我假设没有,因为您每秒调用4次),那么它将使UI无响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM