标签:
Java示例:
package concurrency; import java.util.Random; public class Main6 { public static void main(String[] args) { MyThreadGroup threadGroup = new MyThreadGroup("MyThreadGroup"); Task1 task = new Task1(); for(int i = 0; i < 2;i++){ Thread t = new Thread(threadGroup,task); t.start(); } } } class MyThreadGroup extends ThreadGroup{ /*必须声明带参数的构造器,因为ThreadGroup没有默认的不带参数的构造器*/ public MyThreadGroup(String name) { super(name); } /*重写uncaughtException方法*/ @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(); } } class Task1 implements Runnable{ /*在这个方法里,我们要触发AritmethicException异常,为了达到这个目标, *我们用1000除以一个随机数,当随机数生成器生成0,异常将被抛出*/ @Override public void run() { int result; Random random = new Random(Thread.currentThread().getId()); while(true){ result = 1000/((int)(random.nextDouble()*1000)); System.out.printf("%s : %d\n", Thread.currentThread().getId(),result); if(Thread.currentThread().isInterrupted()){ System.out.printf("%d : Interrupted\n", Thread.currentThread().getId()); return; } } } }
当线程抛出非捕获异常时,JVM将为这个异常寻找3种可能的处理器。首先,寻找抛出这个异常的线程的非捕获异常处理器,如果这个处理器不存在,JVM继续查找这个线程所在的线程组的非捕获异常处理器,这也是本节学习的知识,如果也不存在,JVM将寻找默认的非捕获异常处理器。如果这些处理器都不存在,JVM把堆栈中异常信息打印到控制台,并且退出这个程序。
标签:
原文地址:http://my.oschina.net/fhd/blog/410031