线程组中异常处理

线程组中的一个线程出现异常,该线程停止运行,默认情况下其他线程仍然会继续执行。如果要实现线程组内的一个线程出现异常,其他线程也全部停止该怎么处理?

那么我们需要重新定义ThreadGroup,然后重写uncaughtException方法,处理异常。

class MyThreadGroup extends ThreadGroup{
        public MyThreadGroup(String name) {
            super(name);
        }

        //重写uncaughtException方法
        @Override
        public void uncaughtException(Thread t, Throwable e) {  //t参数是出现异常的线程对象
            System.out.println("捕获到抛出异常线程:" + t.getName());
            System.out.println("捕获到异常信息:" + e.getMessage());
            //如果捕获到线程组内线程的异常,则终止线程组内所有线程
            this.interrupt();
        }
}
package ReentrantLock;

public class t3 {
    public static void main(String[] args) {
        MyThreadGroup group = new MyThreadGroup("我的线程组");
        
        thread[] threadArray = new thread[10];
        
        for(int i=0; i<threadArray.length; i++) {
            threadArray[i] = new thread(group, "正常线程" + (i+1), "1");
            threadArray[i].start();
        }
        
        thread thread1 = new thread(group, "报错线程", "abv");
        thread1.start();        
    }
}

class thread extends Thread    {
    private String num;
    
    public thread(ThreadGroup group, String name, String num) {
        super(group, name);
        this.num = num;
    }
    
    @Override
    public void run() {
        int numInt = Integer.parseInt(num);    //把num转换成整数
        while(this.isInterrupted() == false) {
            System.out.println("死循环中:" + Thread.currentThread().getName());
        }
    }
}

分析:Integer.parseInt()能把()里的内容转换成整数,但是当遇到一些不能转换为整型的字符时,会抛出异常。

当执行 thread thread1 = new thread(group, "报错线程", "abv")时会报错,由于重写了ThreadGroup中的uncaughtException方法,线程组中的其他线程也会一并停止。

 

posted @ 2020-11-10 17:35  Peterxiazhen  阅读(185)  评论(0编辑  收藏  举报