Solution for JavaFX, Java – number of active threads change listener
is Given Below:
in my program I have a status bar and there I indicate the number of active threads, using Thread.activeCount()
, this is all fine but currently this is only updated when I click a button: I read again Thread.activeCount()
and then update the number on the bar — this is not very useful since I have to request “manually” to update the number.
@FXML
public void btnShowThreads() {
btnShowThreads.setText(String.valueOf(Thread.activeCount()));
}
What I need to do is have this on a listener, and I couldn’t find a way to do so. I am trying to avoid to use a timer, e.g. to run every 0.5 seconds to update the number — as threads could be the same number for long periods of time.
How can this be achieved? How can I listen to Thread.activeCount()
changes?
I’m not sure if you can add a “listener” of sorts.. it could be possible. However what about updating certain aspects of your UI on a set interval within a dedicated thread? This is the same approach you’d take to adding a stopwatch or something.
Something like…
// 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){ }
}
};
You can start it with start() and stop it with interrupt()
You can even pause and resume a thread with wait() and notify()
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
As mentioned in the comments, Java doesn’t offer such an option to listen to thread changes. As an alternative, you can use a 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