Count Active Thread in JAVA


 

Count Active Thread in JAVA

In this tutorial, we are using activeCount() method of thread to count the current active threads.

In this tutorial, we are using activeCount() method of thread to count the current active threads.

Count Active Thread in JAVA

In this tutorial, we are using activeCount() method of thread to count the current active threads.

Thread activeCount() :

Thread class provides you to check the current active thread by providing activeCount() method.

activeCount() :  This method returns the total number of active threads in the current thread group.

Example :

class ThreadCount implements Runnable {
	Thread th;
	String str;

	public ThreadCount(String str) {
		this.str = str;
		th = new Thread(this);
		th.start();
	}

	public void run() {
		try {
			Thread.sleep(500);

		} catch (InterruptedException e) {

			e.printStackTrace();
		}
	}
}

class ThreadActiveCount {

	public static void main(String args[]) {
		new ThreadCount("A");
		new ThreadCount("B");
		new ThreadCount("C");
		/* Thread.activeCount() returns active threads */
		System.out
				.println("Number of active threads : " + Thread.activeCount());
	}
}

Output :

Number of active threads : 4

Ads