Skip to content
Advertisement

Count only currently active threads

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.

JavaScript

Advertisement

Answer

tl;dr

Compare the state of the thread:

JavaScript

Here is an example making a stream from your list of Thread objects.

JavaScript

Or count all active threads:

JavaScript

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.

JavaScript

But if you just want a count of all active threads, call Thread.activeCount().

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement