线程的异常捕捉

线程的异常捕捉


之前总结过线程及线程池相关的文章,线程池创建也有多种方式,每种创建线程的方式又各有所异。这次总结子线程中异常的捕捉。

场景

在实际开发中,可能一些业务场景是需要开多条线程执行的,在执行过程中如果出现异常,是否能得到我们所期望的结果是和线程的执行方式有很大关系的。

代码演示

1.为做测试,此处自定义一个线程类:

public class ThreadExceptionRunner implements Runnable {

    public void run() {
    	//子线程中直接抛空指针异常
        throw new RuntimeException("I'm a Exception...");
    }
}

2.测试Demo 类:

public class ThreadExceptionDemo {

    public static void main(String[] args) {

        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10,0L, TimeUnit.MINUTES, new LinkedBlockingQueue());
        // 此处使用的submit
        executor.submit(new ThreadExceptionRunner());
        System.out.println("main finished...");
        executor.shutdown();
    }
}

3.输出结果为:(相安无事),没有报错。
在这里插入图片描述
4.将上面的executor.submit(new ThreadExceptionRunner()); 替换为:executor.execute(new ThreadExceptionRunner());

5.输出结果:异常(这是我们所期望的结果)
在这里插入图片描述
6.分析原因
根据以上的自定义线程类,ThreadExceptionRunner 得知,run()中就是抛异常,所以我们期望的线程在执行时也是抛出异常。查看第一种写法:AbstractExecutorService.submit(Runnable task)

    public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        //此处将task封装成了一个RunnableFuture
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }

再来查看第二种写法:AbstractExecutorService.execute(Runnable command)

public void execute(Runnable command) {
	// 此处省略源码
   }

第一种写法是封装为RunnableFuture 。原因就在这个RunnableFuture ,由于FutureTask<V> implements RunnableFuture,因此此处是创建了一个FutureTask,查看FutureTask.run()
在这里插入图片描述
将异常设置到了outcome对象中:
在这里插入图片描述
查看FutureTask.get()FutureTask.report()

  
   public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
   }

	private V report(int s) throws ExecutionException {
		// 将异常信息赋值给了x
        Object x = outcome;
        
        if (s == NORMAL)
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);
    }

由以上的代码可以得知,我们如果坚持使用submit()的方式,则需要再调用get() 才能获取异常并抛出:

public class ThreadExceptionDemo {

    public static void main(String[] args) {

        ThreadPoolExecutor executorService = new ThreadPoolExecutor(5, 10,0L, TimeUnit.MINUTES, new LinkedBlockingQueue());
        Future<?> submitTask = executorService.submit(new ThreadExceptionRunner());
        try {
            submitTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}

结果如图:
在这里插入图片描述
控制台输出异常:

java.util.concurrent.ExecutionException: java.lang.RuntimeException: I'm a Exception...
	at java.util.concurrent.FutureTask.report(FutureTask.java:122)
	at java.util.concurrent.FutureTask.get(FutureTask.java:192)
	at cn.ibicd.design.mode.factory.test.ThreadExceptionDemo.main(ThreadExceptionDemo.java:15)
Caused by: java.lang.RuntimeException: I'm a Exception...
	at cn.ibicd.design.mode.factory.test.ThreadExceptionRunner.run(ThreadExceptionRunner.java:9)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
	at java.util.concurrent.FutureTask.run(FutureTask.java)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
  1. 上面提供了一种在主线程中捕捉子线程抛出异常的方式,我们还可以在子线程中做统一处理:于是优化上面的写法:
public class ThreadExceptionDemo {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool(new CustomThreadFactory());
        executorService.execute(new ThreadExceptionRunner());
        executorService.shutdown();
    }
}


/**
 * 自定义线程工厂
 */
class CustomThreadFactory implements ThreadFactory {

    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());
        return thread;
    }
}

/**
 * 自定义线程异常捕获Handler
 */
class CustomUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    public void uncaughtException(Thread t, Throwable e) {
        //TODO 处理异常
        System.out.println(e);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值