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
Jul 6, 2021

How to Find the Status of Threads in Java

Finding the status of a thread in Java is a pretty simple task to accomplish. Learn how to do so in this Java programming tutorial. The code below uses methods from the Thread class to achieve this result. Learn how to use the Thread class in Java to find the status of threads:

*/

public class StatusOfThreads {
	public static void main(String[] args) 
	{  
		StatusOfThreads statusOfThreads = new StatusOfThreads();
		statusOfThreads.proceed();
	}

	private void proceed()  
	{
        for (int index = 0; index < 5; index++)
		{
            Thread thread = new Thread(new CustomThread());
            thread.setName("Thread-" + index);
            thread.start();
        }

        int threadCount = 0;
        for (Thread thread : Thread.getAllStackTraces().keySet())
		{
            //Condition to ensure that only current thread group ones are considered.
			//Remove this condition to see the result without this criteria
			if (thread.getThreadGroup() == Thread.currentThread().getThreadGroup()){
                System.out.println("Thread :" + thread + " : " + "State:" + thread.getState());
                ++threadCount;
            }
        }
        System.out.println("Total threads:"+threadCount);
    }
}

class CustomThread implements Runnable
{
    public void run()
	{
        try
		{
            Thread.sleep(1000);
        }catch(Exception exception)
		{
            exception.getMessage();
        }
    }
}

/*

You can expect the following output from the console when you run this Java code:

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