I have a list of Thread and I want to count only currently active threads, but method isAlive() don't work. How correctly is this or exist other method check for currently active threads.
public int activeSize() {
int count = 0;
for (Thread thread : list) {
if (thread.isAlive()) {
count ;
}
}
return count;
}
CodePudding user response:
This function counts all the active Threads in the process:
java.lang.Thread.activeCount();
And of course, you could use getState()
instead of isActive()
to check the current thread's state.
CodePudding user response:
tl;dr
Compare the state of the thread:
thread.getState().equals( Thread.State.RUNNABLE )
Here is an example making a stream from your list of Thread
objects.
threads
.stream()
.filter(
thread -> thread.getState().equals( Thread.State.RUNNABLE )
)
.count() // Or collect them: `.toList()`
Or count all active threads:
Thread.activeCount()
Details
I have no experience in this, but looking the Javadoc for Thread
, I see getState
. That method returns a Thread.State
enum object. Documentation says:
A thread can be in one of the following states, as quoted from the doc:
NEW
A thread that has not yet started is in this state.RUNNABLE
A thread executing in the Java virtual machine is in this state.BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.TERMINATED
A thread that has exited is in this state.
So loop your Thread
objects, fetch their State
, and see if it is RUNNABLE
.
for ( Thread thread : list) {
if ( thread.getState().equals( Thread.State.RUNNABLE ) ) {
…
}
}
But if you just want a count of all active threads, call Thread.activeCount()
.