dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
May 28, 2021

Finding Active Threads in Java Runtime

The following code snippet shows you how to find active threads in the current Java runtime. Java is well-known for its amazing breadth of threading capabilities and the plethora of APIs that support threads.

Feel free to follow along with the code below to better understand how you can locate active threads with Java.

 
*/

public class ActiveThreads
{
	public static void main(String args[]) 
	{

		for (int count = 0; count < 3; count++){
			Thread thread = new Thread(new MyCustomThread());
			thread.setName("MyCustomThread:" + count);
			thread.start();
		}

		int activeThreadCount = Thread.activeCount();
		Thread activeThreads[] = new Thread[activeThreadCount];
		Thread.enumerate(activeThreads);

		System.out.println("Total active threads: " + activeThreadCount);
		for (int i = 0; i < activeThreadCount; i++) {
			System.out.println(i + ": " + activeThreads[i]);
		}
	}
}
   
class MyCustomThread implements Runnable{
	public void run()
	{
		try{
			Thread.sleep(1000);
		}catch(Exception exception){
			System.out.println("Exception: " + exception);
		}
	}
}

/*

If you run this snippet of Java code in your IDE or code editor, you should get the following output:

[root@mypc]# java ActiveThreads
Total active threads: 4
0: Thread[main,5,main]
1: Thread[MyCustomThread:0,5,main]
2: Thread[MyCustomThread:1,5,main]
3: Thread[MyCustomThread:2,5,main]
MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date