JavaFX,Java - 活动线程数更改侦听器

在我的程序中,我有一个状态栏,在那里我使用 Thread.activeCount() 指示活动线程的数量,这一切都很好,但目前这仅在我单击按钮时更新:我再次阅读 {{1 }} 然后更新栏上的数字——这不是很有用,因为我必须“手动”请求更新数字。

Thread.activeCount()

我需要做的是将它放在一个监听器上,但我找不到这样做的方法。我试图避免使用计时器,例如每 0.5 秒运行一次以更新数字——因为线程可能在很长一段时间内都是相同的数字。

如何实现?我如何听取 @FXML public void btnShowThreads() { btnShowThreads.setText(String.valueOf(Thread.activeCount())); } 的更改?

zhangyansong 回答:JavaFX,Java - 活动线程数更改侦听器

我不确定您是否可以添加各种“侦听器”……这是可能的。但是,如何在专用线程中以设定的时间间隔更新 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

大家都在问