use*_*022 15 java user-interface multithreading javafx thread-safety
我随机地以高频率接收数据对象,并且需要使用这些来更新JavaFX GUI.但是,我不想用大量的runnable填充javafx事件队列(我使用Platform.RunLater).
我一直在考虑如何最好地实现限制算法.
有关如何以简短有效的方式为JavaFX Platform.RunLater GUI更新设计限制算法的任何建议?
Jam*_*s_D 18
这是在Task
类中用于实现该updateMessage(...)
方法的习语,以及其他类似的方法.它提供了一个漂亮,强大的解决方案,以避免泛滥FX应用程序线程:
import java.util.concurrent.atomic.AtomicLong;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ThrottlingCounter extends Application {
@Override
public void start(Stage primaryStage) {
final AtomicLong counter = new AtomicLong(-1);
final Label label = new Label();
final Thread countThread = new Thread(new Runnable() {
@Override
public void run() {
long count = 0 ;
while (true) {
count++ ;
if (counter.getAndSet(count) == -1) {
updateUI(counter, label);
}
}
}
});
countThread.setDaemon(true);
countThread.start();
VBox root = new VBox();
root.getChildren().add(label);
root.setPadding(new Insets(5));
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 150, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
private void updateUI(final AtomicLong counter,
final Label label) {
Platform.runLater(new Runnable() {
@Override
public void run() {
final String msg = String.format("Count: %,d", counter.getAndSet(-1));
label.setText(msg);
}
});
}
public static void main(String[] args) {
launch(args);
}
}
Run Code Online (Sandbox Code Playgroud)
在AtomicLong
保持当前值被用来更新标签.计数会不断增加并更新AtomicLong
,但只调度一个调用,Platform.runLater(...)
如果它的当前值为-1.该Platform.runLater(...)
更新Label
从当前值AtomicLong
和翻转AtomicLong
回-1,表明它已经准备好了新的更新.
这里的效果是Platform.runLater(...)
在FX应用程序线程准备好处理它们时安排新的调用.没有硬编码的时间间隔可能需要调整.
归档时间: |
|
查看次数: |
3361 次 |
最近记录: |