java 子線程異常處理

如何在父線程中捕獲來自子線程的異常呢

方法一:子線程中try... catch...

方法二:爲線程設置異常處理器UncaughtExceptionHandler

(異常處理也是在子線程中執行,至關於在子線程中加上了一個異常攔截器,可使用下面的程序驗證)java

(1)Thread.setUncaughtExceptionHandler設置當前線程的異常處理器ide

(2)Thread.setDefaultUncaughtExceptionHandler爲整個程序設置默認的異常處理器函數

(3)new Thread(new ThreadTest() ,new runable{})時傳入 ThreadGroup spa

方法三,經過Future的get方法捕獲子線程異常

 

import java.util.concurrent.*;

public class ThreadTest extends ThreadGroup{

    private ThreadTest(){
        super("ThreadTest");
    }


    public static void main(String[] args) {

        System.out.println(Thread.currentThread().getId());

        Thread t1=new Thread(new ThreadTest(),new Runnable() {//傳入繼承ThreadGroup的類對象
            @Override
            public void run() {

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (1==1){
                    throw new NullPointerException("111");
                }
            }
        });
        t1.start();


        /*ExecutorService executorService = Executors.newFixedThreadPool(8);
        Future future = executorService.submit(()->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (1==1){
                throw new NullPointerException("111");
            }
            return 1;
        });

        try {
            future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {

            //e.getCause().printStackTrace();
            e.printStackTrace();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdownNow();*/


    }

    public   void   uncaughtException(Thread   thread,   Throwable   exception)
    {
        /**
         * 當線程拋出unckecked異常時,系統會自動調用該函數,可是是在拋出異常的線程內執行*/
        System.out.println(Thread.currentThread().getId());
        System.out.println(thread.getId());
        exception.printStackTrace();//example,   print   stack   trace
    }
}

 線程池阻塞方法的使用  future.get()

1.LockSupport.park()消費一個信號量,會一直阻塞,LockSupport.park(thread)增長一個信號量

2.UNSAFE.park(false, 0L) 消費一個信號量 會一直阻塞 UNSAFE.unpark(thread) 增長一個信號量

3.和wait,notify(),notifyAll()相比的優勢

3.1 park 和 unpark無前後順序 而wait,notify(),notifyAll() 有嚴格順序

3.2 park 和 unpark

相關文章
相關標籤/搜索