(一)线程管理_10---Thread Group中处理不可控制的异常

Thread Group中处理不可控制的异常

前面记录的有在线程中处理不可控制的异常,这里记录的是再线程组中处理不可控制的异常,基本上是同样的原理,主要是实现ThreadGroup的uncaughtException方法;java

动手实现

1.实现异常处理方法dom

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.建立线程ide

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)方法;
相关文章
相关标签/搜索