【问题标题】:JavaFX, Java - number of active threads change listenerJavaFX,Java - 活动线程数更改监听器
【发布时间】:2021-10-06 09:37:40
【问题描述】:

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

@FXML
public void btnShowThreads() {
    btnShowThreads.setText(String.valueOf(Thread.activeCount()));
}

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

如何做到这一点?如何收听Thread.activeCount() 的变化?

【问题讨论】:

  • 你不能,至少不能纯粹使用 Java。每半秒运行一次的计时器(或更好的动画)应该没问题。但也请记住,该方法并不完全可靠,如 its documentation 中所述。
  • 如果您控制所有线程/后台任务的创建和执行,您可以创建一个Executor 来跟踪有多少正在运行并将它们提交给该执行程序。如果您在这种情况下操作,这可能是比不断轮询Thread.activeCount() 更好的解决方案;不过,这与您提出问题的方式略有不同。

标签: java multithreading javafx listener


【解决方案1】:

正如 cmets 中所述,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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 你可以阅读这个this关于时间线和线程的帖子。
    • 是的,我做到了!很有帮助!
    猜你喜欢
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 2015-11-01
    相关资源
    最近更新 更多