多线程异常处理机制

thread异常处理

@org.junit.Test
    public void test(){
        try{
            Thread t = new Thread(() -> {
                System.out.println("test thread");
                System.out.println(1/0);
            });
            t.start();
        } catch (Exception e){
            System.out.println("catch exception");
        }
    }

可以看到没有打印出catch exception,说明没有捕获到异常,在多线程的时候,我们在线程外面是捕获不到异常的
在这里插入图片描述

@org.junit.Test
    public void test(){
        Thread t = new Thread(() -> {
            try{
                System.out.println("test thread");
                System.out.println(1/0);
            } catch (Exception e){
            System.out.println("catch exception");
            }
        });
        t.start();
    }
   
  

在这里插入图片描述
可以看到,在线程里面可以捕获到异常。

FutureTask异常处理

class ExceptionCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println("run");
        throw new RuntimeException("exception throw");
    }
}
@org.junit.Test
    public void futureTaskTest(){
        FutureTask<String> task = new FutureTask<>(new ExceptionCallable());
        Thread thread = new Thread(task);
        thread.setUncaughtExceptionHandler((t, e) ->
                System.out.println("catch exception"+ t.getName()+ e));
        thread.start();
        
    }

在这里插入图片描述
可以看到并没有捕获到异常,需要在future的get()来捕获异常才可以。

try{
            task.get();
        } catch (Exception e){
            System.out.println("catch exception"+e.getMessage());
        }

在这里插入图片描述

ThreadPoolExcutor线程池的异常处理:

使用execute提交线程的情况

这种情况如果我们没有在线程内捕获异常那么JVM会调用
Thread的UncaughtExceptionHandler的uncaughtException方法来处理异常,这是我们可以自己写逻辑覆盖其方法

public class MyHandler implements Thread.UncaughtExceptionHandler{
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("threadId = {}, threadName = {}, ex = {}"
                +t.getId()+ t.getName()+ e.getMessage());
    }
}

测试代码:

public static void main(String[] args){
        ExecutorService es = new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactoryBuilder().setUncaughtExceptionHandler(new MyHandler()).build());
        es.execute(() -> {
            System.out.println(1/0);
        });
        System.out.println("x");
        es.shutdown();

    }

运行结果如下,说明最终执行到了我们自定义的异常捕获方法。
在这里插入图片描述

使用submit提交线程的情况

submit会返回一个Future对象,我们要catct,Future的get()来捕获异常

ExecutorService es = new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactoryBuilder().setUncaughtExceptionHandler(new MyHandler()).build());
        Future ft = es.submit(() -> {
            System.out.println(1/0);
            //System.out.println("x1");
        });

        try{
            ft.get();
        } catch (Exception e){
            System.out.println("catch exception = {},"+e.getMessage());
        }

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值