【多线程】线程异常知多少?

1.常见问题

1.1 Java异常体系图
1.2 实际工作中,如何全局处理异常?为什么要全局处理?不处理行不行?
1.3 run方法是否可以抛出异常?如果抛出异常,线程的状态会怎么样?

run()方法不可以向上抛出异常,只可以自己捕获,抛出异常后,线程停止运行,进入终止状态

2. 线程的未捕获异常UncaughtException应该如何处理?

2.1 为什么需要UncaughtExceptionHandler?
  • 主线程可以轻松发现异常,子线程却不行
/**
 * 描述:单线程,抛出处理,有异常堆栈
 * 多线程,子线程发生异常,会有什么不同?
 * */
public class ExceptionInChildThread implements Runnable{
    @Override
    public void run() {

        throw new RuntimeException("运行出错");
    }

    public static void main(String[] args) {

        new Thread(new ExceptionInChildThread()).start();

        for (int i = 0; i < 1000; i++) {
            System.out.println(i);
        }
    }
}

输出结果

在这里插入图片描述

程序结果分析

从输出结果来看,子线程抛出异常,主线程并没有停止,而是继续执行,这就造成在实际生产过程中可能遗漏子线程异常信息

  • 子线程异常无法用传统方法捕获

/**
 * 1.不加try catch抛出4个异常,都是带线程名
 * 2. 加了 try catch,期望捕获到第一个线程的异常,线程234不应该运行,希望看到打印出caught Exception
 * 3. 执行时发现,根本没有Caught Exception,线程234依然运行并且抛出异常。
 *
 * 说明线程的异常不能用传统方法捕获。
 * try catch只能捕获对应线程内的异常
 * */
public class CantCatchDirectly implements Runnable{
    @Override
    public void run() {
        throw new RuntimeException(Thread.currentThread().getName() + "caught exception");
    }

    public static void main(String[] args) throws InterruptedException {

        try{

            new Thread(new CantCatchDirectly(),"whale").start();
            TimeUnit.MILLISECONDS.sleep(300);
            new Thread(new CantCatchDirectly(),"shark").start();
            TimeUnit.MILLISECONDS.sleep(300);
            new Thread(new CantCatchDirectly(),"salmon").start();
            TimeUnit.MILLISECONDS.sleep(300);
            new Thread(new CantCatchDirectly(),"regalecus glesne").start();

        }catch (RuntimeException e){
            System.out.println("catch exception ");
        }

    }
}

输出结果

Exception in thread "shark" Exception in thread "salmon" Exception in thread "whale" Exception in thread "regalecus glesne" java.lang.RuntimeException: sharkcaught exception
	at com.whaleson.threadcoreknowledge.uncaughtexception.CantCatchDirectly.run(CantCatchDirectly.java:14)
	at java.lang.Thread.run(Thread.java:748)
java.lang.RuntimeException: regalecus glesnecaught exception
	at com.whaleson.threadcoreknowledge.uncaughtexception.CantCatchDirectly.run(CantC
	atchDirectly.java:14)
	at java.lang.Thread.run(Thread.java:748)
java.lang.RuntimeException: whalecaught exception
	at com.whaleson.threadcoreknowledge.uncaughtexception.CantCatchDirectly.run(CantCatchDirectly.java:14)
	at java.lang.Thread.run(Thread.java:748)
java.lang.RuntimeException: salmoncaught exception
	at com.whaleson.threadcoreknowledge.uncaughtexception.CantCatchDirectly.run(CantCatchDirectly.java:14)
	at java.lang.Thread.run(Thread.java:748)

Process finished with exit code 0

程序结果分析

从输出结果来看,线程whale抛出,主线程并没有捕获异常,这是因为try catch只能捕获对应线程内的异常

  • 不能直接捕获的后果、提高健壮性
2.2 两种解决方案
  • 方案一(不推荐):手动在每个run方法里进行try catch
public class CantCatchDirectly implements Runnable{
    @Override
    public void run() {
        try{

            throw new RuntimeException(Thread.currentThread().getName() + "caught exception");

        }catch (RuntimeException e){

            System.out.println("Caught exception.");

        }
    }

    public static void main(String[] args) throws InterruptedException {

        new Thread(new CantCatchDirectly(),"whale").start();
        TimeUnit.MILLISECONDS.sleep(300);
        new Thread(new CantCatchDirectly(),"shark").start();
        TimeUnit.MILLISECONDS.sleep(300);
        new Thread(new CantCatchDirectly(),"salmon").start();
        TimeUnit.MILLISECONDS.sleep(300);
        new Thread(new CantCatchDirectly(),"regalecus glesne").start();

    }
}

  • 方案二(推荐):利用UncaughtException
    • UncaughtExceptionHandler接口
    • void uncaughtException(Thread t, Throwable e);
    • 异常处理器的调用策略
public class ThreadGroup implements Thread.UncaughtExceptionHandler {
	public void uncaughtException(Thread t, Throwable e) {
        if (parent != null) {
            parent.uncaughtException(t, e);
        } else {
            Thread.UncaughtExceptionHandler ueh =
                Thread.getDefaultUncaughtExceptionHandler();
            if (ueh != null) {
                ueh.uncaughtException(t, e);
            } else if (!(e instanceof ThreadDeath)) {
                System.err.print("Exception in thread \""
                                 + t.getName() + "\" ");
                e.printStackTrace(System.err);
            }
        }
    }
}
自定义实现未处理异常

需要实现Thread.UncaughtExceptionHandler

import java.util.logging.Level;
import java.util.logging.Logger;

public class SharkUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        Logger logger = Logger.getAnonymousLogger();
        logger.log(Level.WARNING, " thread has exception " + t.getName());
        System.out.println(" current thread name is " + t.getName() + " exception message : " + e.getMessage());
    }

}

将自定义的未捕获异常处理器添加到线程中。

public class UseOwnUncaughtExceptionHandler implements Runnable{

    @Override
    public void run() {
        throw new RuntimeException(Thread.currentThread().getName() + "caught exception");
    }

    public static void main(String[] args) throws InterruptedException {
        Thread.setDefaultUncaughtExceptionHandler(new SharkUncaughtExceptionHandler());
        new Thread(new UseOwnUncaughtExceptionHandler(), "whale").start();
        TimeUnit.MILLISECONDS.sleep(300);
        new Thread(new UseOwnUncaughtExceptionHandler(),"shark").start();
        TimeUnit.MILLISECONDS.sleep(300);
        new Thread(new UseOwnUncaughtExceptionHandler(),"salmon").start();
        TimeUnit.MILLISECONDS.sleep(300);
        new Thread(new UseOwnUncaughtExceptionHandler(),"regalecus glesne").start();
    }
}

输出结果

一月 02, 2022 8:12:42 下午 com.whaleson.threadcoreknowledge.uncaughtexception.SharkUncaughtExceptionHandler uncaughtException
警告:  thread has exception whale
 current thread name is whale exception message : whalecaught exception
一月 02, 2022 8:12:42 下午 com.whaleson.threadcoreknowledge.uncaughtexception.SharkUncaughtExceptionHandler uncaughtException
警告:  thread has exception shark
 current thread name is shark exception message : sharkcaught exception
一月 02, 2022 8:12:43 下午 com.whaleson.threadcoreknowledge.uncaughtexception.SharkUncaughtExceptionHandler uncaughtException
警告:  thread has exception salmon
 current thread name is salmon exception message : salmoncaught exception
 current thread name is regalecus glesne exception message : regalecus glesnecaught exception
一月 02, 2022 8:12:43 下午 com.whaleson.threadcoreknowledge.uncaughtexception.SharkUncaughtExceptionHandler uncaughtException
警告:  thread has exception regalecus glesne

使用lambda表达式自定义未捕获异常处理器

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UseOwnUncaughtExceptionHandler implements Runnable{

    @Override
    public void run() {
        throw new RuntimeException(Thread.currentThread().getName() + "caught exception");
    }

    public static void main(String[] args) throws InterruptedException {

        Thread.UncaughtExceptionHandler uncaughtExceptionHandler = (t, e)->{
            Logger logger = Logger.getAnonymousLogger();
            logger.log(Level.WARNING, " thread has exception " + t.getName());
            System.out.println(" current thread name is " + t.getName() + " exception message : " + e.getMessage());
        };
        Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);

        new Thread(new UseOwnUncaughtExceptionHandler(), "whale").start();
        TimeUnit.MILLISECONDS.sleep(300);
        new Thread(new UseOwnUncaughtExceptionHandler(),"shark").start();
        TimeUnit.MILLISECONDS.sleep(300);
        new Thread(new UseOwnUncaughtExceptionHandler(),"salmon").start();
        TimeUnit.MILLISECONDS.sleep(300);
        new Thread(new UseOwnUncaughtExceptionHandler(),"regalecus glesne").start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值