我不确定您是否可以添加各种“侦听器”……这是可能的。但是,如何在专用线程中以设定的时间间隔更新 UI 的某些方面呢?这与添加秒表或其他东西的方法相同。
有点像……
// pesudo code
Thread uiUpdated = () -> {
while(!Thread.interrupted()) {
// Update on FX thread - other will cause error
Platform.runLater(() -> {
// Update your UI here
myNode.setText("Idk some text here");
});
// Only update the UI every 1s
try {
Thread.sleep(1000);
} catch (InterruptedException ignored){ }
}
};
可以用start()启动,用interrupt()停止
您甚至可以使用 wait() 和 notify()
暂停和恢复线程
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
,
正如评论中提到的,Java 没有提供这样一个选项来监听线程变化。作为替代方案,您可以使用 Timeline
:
// a Timeline with a KeyFrame that runs for 1 second and updates the value when the cycle finishes
Timeline updater = new Timeline(new KeyFrame(Duration.seconds(1),event -> {
activeThreadsLabel.setText("Threads: " + Thread.activeCount());
event.consume();
}));
updater.setCycleCount(Animation.INDEFINITE); // run indefinitly
updater.play(); // start
本文链接:https://www.f2er.com/7125.html