栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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);
        }
    }
}

输出结果

程序结果分析

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

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

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();
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/692752.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号