(一)線程管理_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)方法;
相關文章
相關標籤/搜索