Home Tutorial Java Core Java :Thread Enumeration

 
 

Share on Google+Share on Google+
Java :Thread Enumeration
Posted on: November 6, 2012 at 12:00 AM
Advertisement
In this tutorial you will learn about java thread enumeration.

Java :Thread Enumeration

In this tutorial you will learn about java thread enumeration.

Thread Enumeration :

For enumeration, thread uses two methods activeCount() and enumerate(). activeCount() method returns count of all active threads. This count size is used for array of Thread references. Calculating the size of array, it is given to the enumerate() method.

public static int enumerate(Thread[] tarray) - This method copies all active threads in the current thread's thread group and its subgroups.
It takes array of Thread objects as argument. It returns the number of threads which are put into the array. This method throws SecurityException.

Example : In this example we are using enumerate() method of thread.


class ThreadEnumeration implements Runnable {

	public void run() {
		Thread thread = Thread.currentThread();
		try {
			thread.sleep(100);
		} catch (Exception e) {
		}
		System.out.println("Starting " + thread.getName() + "...");
		for (int i = 0; i <= 1; i++) {
			System.out.println(i);
		}
		System.out.println(Thread.currentThread().getName()
				+ " has finished executing.");
	}

	public static void main(String args[]) {

		ThreadGroup threadGroup1 = new ThreadGroup("ThreadGroup1");
		ThreadGroup threadGroup2 = new ThreadGroup("ThreadGroup2");

		new Thread(threadGroup1, new ThreadEnumeration()).start();
		new Thread(threadGroup2, new ThreadEnumeration()).start();

		Thread[] threads = new Thread[threadGroup1.activeCount()];
		int numThreads = threadGroup1.enumerate(threads, true);
		for (int i = 0; i < numThreads; i++) {
			System.out.println("Found Thread " + threads[i].getName());
		}
	}
}

Output :

Found Thread Thread-0
Starting Thread-1...
0
1
Thread-1 has finished executing.
Starting Thread-0...
0
1
Thread-0 has finished executing.

Advertisement

Related Tags for Java :Thread Enumeration:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 6, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com