3

Is there a way to print out all the threads and its id, status using code?

For example, I have 5 threads, and I want to enumerate all of them.

Adam Lee
  • 24,710
  • 51
  • 156
  • 236

3 Answers3

2

You can do as below.

Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

for (Thread thread: threadSet) {
 System.out.println(thread.getId());
}

Make sure you read and understand the method Thread.getAllStackTraces() before using them.

Jayamohan
  • 12,734
  • 2
  • 27
  • 41
1

Use Thread.currentThread().getId();

rajesh
  • 3,247
  • 5
  • 31
  • 56
-1

Assign the thread object to a public variable if you need to control the thread from other parts of the program, or print it out directly if you just want to know what's running:

public int myThreadId = 0;

public void run () {

System.out.println("Thread Name: " + Thread.currentThread().getName(); // Printing the thread name

myThreadId = Thread.currentThread().getId(); // Assigning the thread ID to a public variable

}

Read more: How to Get a Reference to a Java Thread | eHow.com http://www.ehow.com/how_6879305_reference-java-thread.html#ixzz2FfEUe3cF

Also

Get a handle to the root ThreadGroup, like this:

ThreadGroup rootGroup = Thread.currentThread( ).getThreadGroup( );
ThreadGroup parentGroup;
while ( ( parentGroup = rootGroup.getParent() ) != null ) {
    rootGroup = parentGroup;
}

Now, call the enumerate() function on the root group repeatedly. The second argument lets you get all threads, recursively:

Thread[] threads = new Thread[ rootGroup.activeCount() ];
while ( rootGroup.enumerate( threads, true ) == threads.length ) {
    threads = new Thread[ threads.length * 2 ];
}

Note how we call enumerate() repeatedly until the array is large enough to contain all entries.

Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76