主线程感知其他线程中的异常方法

1.采用CountDownLatch来等待线程走完;
2.用AtomicReference 对对象封装的原子性,获得多个线程的异常情况
final CountDownLatch countDownLatch = new CountDownLatch(1);
        final AtomicReference exceptionReference = new AtomicReference();

new Thread(new Runnable(){

                @Override
                public void run() {
                    try {
                  
                    }
                    catch (InitErrorException e) {
                        exceptionReference.set(e);
                    }
                    catch (Exception e) {
                        exceptionReference.set(new Exception("error!", e));
                    }
                    finally {
                        countDownLatch .countDown();
                    }
                }
            }).start();

registryDownLatch.await();
            Exception initErrorException = (Exception)exceptionReference.get();

 if (initErrorException != null) {
                throw Exception;
            }
原文地址:https://www.cnblogs.com/becoding/p/13418533.html