Thread Group中处理不可控制的异常
前面记录的有在线程中处理不可控制的异常,这里记录的是再线程组中处理不可控制的异常,基本上是一样的原理,主要是实现ThreadGroup的uncaughtException方法;
动手实现
1.实现异常处理方法
public class MyThreadGroup extends ThreadGroup {
public MyThreadGroup(String name) {
super(name);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.printf("The thread %s has thrown an Exception\n",t.getId());
e.printStackTrace(System.out);
System.out.printf("Terminating the rest of the Threads\n");
interrupt();
}
}
2.创建线程
public class Task implements Runnable {
@Override
public void run() {
int result;
Random random=new Random(Thread.currentThread().getId());
while (true) {
result=1000/((int)(random.nextDouble()*1000));
// This line will throw IllegalFormatConversionException
System.out.printf("%s : %f\n",Thread.currentThread().getId(),result);
if (Thread.currentThread().isInterrupted()) {
System.out.printf("%d : Interrupted\n",Thread.currentThread().getId());
return;
}
}
}
public static void main(String[] args) {
MyThreadGroup threadGroup=new MyThreadGroup("MyThreadGroup");
Task task=new Task();
for (int i=0; i<2; i++){
Thread t=new Thread(threadGroup,task);
t.start();
}
}
}
要点
不论是在线程中处理异常还是在Thread Group中处理异常,都需要实现异常处理方法;不同的是:
- 线程中处理异常需要实现Thread.UncaughtExceptionHandler类,重写public void uncaughtException(Thread t, Throwable e)方法;
- Thread Group中需要集成ThreadGroup类,重写public void uncaughtException(Thread t, Throwable e)方法;