Java provides ThreadGroup class. A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent.
Extend this class and implement uncaughtException(Thread t, Throwable e) method. This method would be called by the Java Virtual Machine when a thread in this thread group stops because of an uncaught exception.
Create child thread add this thread to a thread group.
Code below explains this further.
class ThreadExample extends Thread
{
String Request;
ThreadExample(ThreadGroup tg,String varRequestID)
{
super(tg,varRequestID);
Request = varRequestID;
System.out.println(this);
start();
}
public void run()
{
System.out.println("Request " + Request + " started");
try
{
Thread.sleep(5000);
}
catch(Exception e)
{
}
// let us create out of memory exception
String s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
while(true)
{
s = s + s + s + s;
}
}
}
class Test
{
public static class ThreadGroupExample extends ThreadGroup {
public ThreadGroupExample(String s) {
super(s);
}
public void uncaughtException(Thread thread, Throwable throwable) {
System.out.println("Thread " + thread.getName()
+ " died, exception was: ");
throwable.printStackTrace();
}
}
public static void main(String args[])
{
int i = 1;
// Create thread group
ThreadGroupExample tg = new ThreadGroupExample("JC");
while (i <= 4) { try { // Create new thread and add to thread group ThreadExample objDEE = new ThreadExample(tg,Integer.toString(i)); System.out.println("ThreadGroupName: " + objDEE.getThreadGroup().getName()); } catch (Exception e) { System.out.println("Main"); e.printStackTrace(); } i = i + 1; } // list number of running thread in thread group while(true) { int tCount = tg.activeCount(); System.out.println("Thread Count " + Integer.toString(tCount)); Thread[] tArray = new Thread[tCount + 2]; int count = tg.enumerate(tArray); for(int j = 1;j <= count;j++) { System.out.println(tArray[j-1].toString()); } try { Thread.sleep(2000); } catch(Exception e) { } } } }
No comments:
Post a Comment