成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

線程池中線程拋了異常,該如何處理?

開發 前端
submit不打印異常信息,而execute則會打印異常信息!,submit的方式不打印異常信息,顯然在生產中,是不可行的,因為我們無法保證線程中的任務永不異常,而如果使用submit的方式出現了異常,直接如上寫法,我們將無法獲取到異常信息,做出對應的判斷和處理,所以下一步需要知道如何獲取線程池拋出的異常!

在實際開發中,我們常常會用到線程池,但任務一旦提交到線程池之后,如果發生異常之后,怎么處理? 怎么獲取到異常信息?在了解這個問題之前,可以先看一下 線程池的源碼解析,從源碼中我們知道了線程池的提交方式:submit和execute的區別,接下來分別使用他們執行帶有異常的任務!看結果是怎么樣的!

我們先用偽代碼模擬一下線程池拋異常的場景:

public class ThreadPoolException {
    public static void main(String[] args) {

        //創建一個線程池
        ExecutorService executorService= Executors.newFixedThreadPool(1);

        //當線程池拋出異常后 submit無提示,其他線程繼續執行
        executorService.submit(new task());

        //當線程池拋出異常后 execute拋出異常,其他線程繼續執行新任務
        executorService.execute(new task());
    }
}

//任務類
class task implements  Runnable{

    @Override
    public void run() {
        System.out.println("進入了task方法!!!");
        int i=1/0;

    }
}

運行結果:

圖片圖片

可以看到:submit不打印異常信息,而execute則會打印異常信息!,submit的方式不打印異常信息,顯然在生產中,是不可行的,因為我們無法保證線程中的任務永不異常,而如果使用submit的方式出現了異常,直接如上寫法,我們將無法獲取到異常信息,做出對應的判斷和處理,所以下一步需要知道如何獲取線程池拋出的異常!

推薦Java工程師技術指南:https://github.com/chenjiabing666/JavaFamily

submit()想要獲取異常信息就必須使用get()方法!!

//當線程池拋出異常后 submit無提示,其他線程繼續執行
Future<?> submit = executorService.submit(new task());
submit.get();

submit打印異常信息如下:

圖片圖片

方案一:使用 try -catch

public class ThreadPoolException {
    public static void main(String[] args) {
        
        //創建一個線程池
        ExecutorService executorService = Executors.newFixedThreadPool(1);

        //當線程池拋出異常后 submit無提示,其他線程繼續執行
        executorService.submit(new task());

        //當線程池拋出異常后 execute拋出異常,其他線程繼續執行新任務
        executorService.execute(new task());
    }
}
// 任務類
class task implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println("進入了task方法!!!");
            int i = 1 / 0;
        } catch (Exception e) {
            System.out.println("使用了try -catch 捕獲異常" + e);
        }
    }
}

打印結果:

圖片圖片

可以看到 submit 和 execute都清晰易懂的捕獲到了異常,可以知道我們的任務出現了問題,而不是消失的無影無蹤。關注公眾號:碼猿技術專欄,回復關鍵詞:1111 獲取阿里內部Java性能調優手冊!

方案二:使用Thread.setDefaultUncaughtExceptionHandler方法捕獲異常

方案一中,每一個任務都要加一個try-catch 實在是太麻煩了,而且代碼也不好看,那么這樣想的話,可以用Thread.setDefaultUncaughtExceptionHandler方法捕獲異常

圖片圖片

UncaughtExceptionHandler 是Thread類一個內部類,也是一個函數式接口。

推薦Java工程師技術指南:https://github.com/chenjiabing666/JavaFamily

內部的uncaughtException是一個處理線程內發生的異常的方法,參數為線程對象t和異常對象e。

圖片圖片

應用在線程池中如下所示:重寫它的線程工廠方法,在線程工廠創建線程的時候,都賦予UncaughtExceptionHandler處理器對象。

public class ThreadPoolException {
    public static void main(String[] args) throws InterruptedException {


        //1.實現一個自己的線程池工廠
        ThreadFactory factory = (Runnable r) -> {
            //創建一個線程
            Thread t = new Thread(r);
            //給創建的線程設置UncaughtExceptionHandler對象 里面實現異常的默認邏輯
            t.setDefaultUncaughtExceptionHandler((Thread thread1, Throwable e) -> {
                System.out.println("線程工廠設置的exceptionHandler" + e.getMessage());
            });
            return t;
        };

        //2.創建一個自己定義的線程池,使用自己定義的線程工廠
        ExecutorService executorService = new ThreadPoolExecutor(
                1,
                1,
                0,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue(10),
                factory);

        // submit無提示
        executorService.submit(new task());

        Thread.sleep(1000);
        System.out.println("==================為檢驗打印結果,1秒后執行execute方法");

        // execute 方法被線程工廠factory 的UncaughtExceptionHandler捕捉到異常
        executorService.execute(new task());


    }


}

class task implements Runnable {
    @Override
    public void run() {
        System.out.println("進入了task方法!!!");
        int i = 1 / 0;
    }
}

打印結果如下:

圖片圖片

根據打印結果我們看到,execute方法被線程工廠factory中設置的 UncaughtExceptionHandler捕捉到異常,而submit方法卻沒有任何反應!說明UncaughtExceptionHandler在submit中并沒有被調用。這是為什么呢?

在日常使用中,我們知道,execute和submit最大的區別就是execute沒有返回值,submit有返回值。submit返回的是一個future ,可以通過這個future取到線程執行的結果或者異常信息。

Future<?> submit = executorService.submit(new task());
//打印異常結果
  System.out.println(submit.get());

圖片圖片

從結果看出:submit并不是丟失了異常,使用future.get()還是有異常打印的!!那為什么線程工廠factory 的UncaughtExceptionHandler沒有打印異常呢?猜測是submit方法內部已經捕獲了異常, 只是沒有打印出來,也因為異常已經被捕獲,因此jvm也就不會去調用Thread的UncaughtExceptionHandler去處理異常。

接下來,驗證猜想:

首先看一下submit和execute的源碼:

execute方法的源碼在這博客中寫的很詳細,點擊查看execute源碼,在此就不再啰嗦了

https://blog.csdn.net/qq_45076180/article/details/108316340

submit源碼在底層還是調用的execute方法,只不過多一層Future封裝,并返回了這個Future,這也解釋了為什么submit會有返回值

//submit()方法
 public <T> Future<T> submit(Callable<T> task) {
     if (task == null) throw new NullPointerException();
     
     //execute內部執行這個對象內部的邏輯,然后將結果或者異常 set到這個ftask里面
     RunnableFuture<T> ftask = newTaskFor(task); 
     // 執行execute方法
     execute(ftask); 
     //返回這個ftask
     return ftask;
 }

可以看到submit也是調用的execute,在execute方法中,我們的任務被提交到了addWorker(command, true) ,然后為每一個任務創建一個Worker去處理這個線程,這個Worker也是一個線程,執行任務時調用的就是Worker的run方法!run方法內部又調用了runworker方法!如下所示:

public void run() {
        runWorker(this);
 }
     
final void runWorker(Worker w) {
     Thread wt = Thread.currentThread();
     Runnable task = w.firstTask;
     w.firstTask = null;
     w.unlock(); // allow interrupts
     boolean completedAbruptly = true;
     try {
      //這里就是線程可以重用的原因,循環+條件判斷,不斷從隊列中取任務        
      //還有一個問題就是非核心線程的超時刪除是怎么解決的
      //主要就是getTask方法()見下文③
         while (task != null || (task = getTask()) != null) {
             w.lock();
             if ((runStateAtLeast(ctl.get(), STOP) ||
                  (Thread.interrupted() &&
                   runStateAtLeast(ctl.get(), STOP))) &&
                 !wt.isInterrupted())
                 wt.interrupt();
             try {
                 beforeExecute(wt, task);
                 Throwable thrown = null;
                 try {
                  //執行線程
                     task.run();
                     //異常處理
                 } catch (RuntimeException x) {
                     thrown = x; throw x;
                 } catch (Error x) {
                     thrown = x; throw x;
                 } catch (Throwable x) {
                     thrown = x; throw new Error(x);
                 } finally {
                  //execute的方式可以重寫此方法處理異常
                     afterExecute(task, thrown);
                 }
             } finally {
                 task = null;
                 w.completedTasks++;
                 w.unlock();
             }
         }
         //出現異常時completedAbruptly不會被修改為false
         completedAbruptly = false;
     } finally {
      //如果如果completedAbruptly值為true,則出現異常,則添加新的Worker處理后邊的線程
         processWorkerExit(w, completedAbruptly);
     }
 }

核心就在 task.run(); 這個方法里面了, 期間如果發生異常會被拋出。

  • 如果用execute提交的任務,會被封裝成了一個runable任務,然后進去 再被封裝成一個worker,最后在worker的run方法里面調用runWoker方法, runWoker方法里面執行任務任務,如果任務出現異常,用try-catch捕獲異常往外面拋,我們在最外層使用try-catch捕獲到了 runWoker方法中拋出的異常。因此我們在execute中看到了我們的任務的異常信息。
  • 那么為什么submit沒有異常信息呢? 因為submit是將任務封裝成了一個futureTask ,然后這個futureTask被封裝成worker,在woker的run方法里面,最終調用的是futureTask的run方法, 猜測里面是直接吞掉了異常,并沒有拋出異常,因此在worker的runWorker方法里面無法捕獲到異常。

下面來看一下futureTask的run方法,果不其然,在try-catch中吞掉了異常,將異常放到了 setException(ex);里面

public void run() {
     if (state != NEW ||
         !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                      null, Thread.currentThread()))
         return;
     try {
         Callable<V> c = callable;
         if (c != null && state == NEW) {
             V result;
             boolean ran;
             try {
                 result = c.call();
                 ran = true;
             } catch (Throwable ex) {
                 result = null;
                 ran = false;
                 //在此方法中設置了異常信息
                 setException(ex);
             }
             if (ran)
                 set(result);
         }
         //省略下文
 。。。。。。
setException(ex)`方法如下:將異常對象賦予`outcome
protected void setException(Throwable t) {
       if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        //將異常對象賦予outcome,記住這個outcome,
           outcome = t;
           UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
           finishCompletion();
       }
   }

將異常對象賦予outcome有什么用呢?這個outcome是什么呢?當我們使用submit返回Future對象,并使用Future.get()時, 會調用內部的report方法!

public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    //注意這個方法
    return report(s);
}

reoport里面實際上返回的是outcome ,剛好之前的異常就set到了這個outcome里面

private V report(int s) throws ExecutionException {
 //設置`outcome`
    Object x = outcome;
    if (s == NORMAL)
     //返回`outcome`
        return (V)x;
    if (s >= CANCELLED)
        throw new CancellationException();
    throw new ExecutionException((Throwable)x);
}

因此,在用submit提交的時候,runable對象被封裝成了future ,future 里面的 run方法在處理異常時, try-catch了所有的異常,通過setException(ex);方法設置到了變量outcome里面, 可以通過future.get獲取到outcome。

所以在submit提交的時候,里面發生了異常, 是不會有任何拋出信息的。而通過future.get()可以獲取到submit拋出的異常!在submit里面,除了從返回結果里面取到異常之外, 沒有其他方法。因此,在不需要返回結果的情況下,最好用execute ,這樣就算沒有寫try-catch,疏漏了異常捕捉,也不至于丟掉異常信息。

方案三:重寫afterExecute進行異常處理

通過上述源碼分析,在excute的方法里面,可以通過重寫afterExecute進行異常處理,但是注意! 這個也只適用于excute提交(submit的方式比較麻煩,下面說),因為submit的task.run里面把異常吞了,根本不會跑出來異常,因此也不會有異常進入到afterExecute里面。

在runWorker里面,調用task.run之后,會調用線程池的 afterExecute(task, thrown) 方法

final void runWorker(Worker w) {
//當前線程
        Thread wt = Thread.currentThread();
        //我們的提交的任務
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            while (task != null || (task = getTask()) != null) {
                w.lock();
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                    //直接就調用了task的run方法 
                        task.run(); //如果是futuretask的run,里面是吞掉了異常,不會有異常拋出,
                       // 因此Throwable thrown = null;  也不會進入到catch里面
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                    //調用線程池的afterExecute方法 傳入了task和異常
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

重寫afterExecute處理execute提交的異常

public class ThreadPoolException3 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {


        //1.創建一個自己定義的線程池
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                3,
                0,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue(10)
        ) {
            //重寫afterExecute方法
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                System.out.println("afterExecute里面獲取到異常信息,處理異常" + t.getMessage());
            }
        };
        
        //當線程池拋出異常后 execute
        executorService.execute(new task());
    }
}

class task3 implements Runnable {
    @Override
    public void run() {
        System.out.println("進入了task方法!!!");
        int i = 1 / 0;
    }
}

執行結果:我們可以在afterExecute方法內部對異常進行處理

如果要用這個afterExecute處理submit提交的異常, 要額外處理。判斷Throwable是否是FutureTask,如果是代表是submit提交的異常,代碼如下:

public class ThreadPoolException3 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {


        //1.創建一個自己定義的線程池
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                3,
                0,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue(10)
        ) {
            //重寫afterExecute方法
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                //這個是excute提交的時候
                if (t != null) {
                    System.out.println("afterExecute里面獲取到excute提交的異常信息,處理異常" + t.getMessage());
                }
                //如果r的實際類型是FutureTask 那么是submit提交的,所以可以在里面get到異常
                if (r instanceof FutureTask) {
                    try {
                        Future<?> future = (Future<?>) r;
                        //get獲取異常
                        future.get();

                    } catch (Exception e) {
                        System.out.println("afterExecute里面獲取到submit提交的異常信息,處理異常" + e);
                    }
                }
            }
        };
        //當線程池拋出異常后 execute
        executorService.execute(new task());
        
        //當線程池拋出異常后 submit
        executorService.submit(new task());
    }
}

class task3 implements Runnable {
    @Override
    public void run() {
        System.out.println("進入了task方法!!!");
        int i = 1 / 0;
    }
}

處理結果如下:

圖片圖片

可以看到使用重寫afterExecute這種方式,既可以處理execute拋出的異常,也可以處理submit拋出的異常

責任編輯:武曉燕 來源: 碼猿技術專欄
相關推薦

2023-02-02 08:56:25

線程池線程submit

2025-02-05 14:28:19

2024-04-02 09:53:08

線程池線程堆棧

2024-06-13 09:30:33

Java線程池線程

2024-10-11 16:57:18

2023-03-09 12:21:38

2010-03-17 09:33:30

Java多線程方案

2024-08-30 08:23:06

2019-09-26 10:19:27

設計電腦Java

2022-12-28 08:17:19

異常處理code

2025-02-04 11:45:23

2020-02-26 15:12:43

線程池增長回收

2011-06-01 11:23:09

Android 線程

2021-06-17 06:57:10

SpringBoot線程池設置

2010-04-14 09:20:26

.NET多線程

2012-01-16 09:00:56

線程

2024-04-08 10:09:37

TTLJava框架

2012-07-03 11:18:20

運維disable tab

2025-03-31 08:04:50

MySQLCPU內存

2010-02-23 17:12:01

WCF字符串
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 亚洲成人精品 | 91久久久久 | 国产在线观看不卡一区二区三区 | 成人在线观看中文字幕 | 国产成人在线视频 | 成人毛片视频在线播放 | 亚洲高清视频一区二区 | 成人av一区二区在线观看 | 无码一区二区三区视频 | 免费一区二区三区 | 久久久久九九九女人毛片 | 免费在线观看成人 | 国产日韩免费观看 | 日韩a视频| 成人久久18免费网站图片 | 国产一区二区三区久久 | 爱爱爱av | 91久久久久 | 韩日一区二区 | 欧美国产精品一区二区 | 欧美网站一区 | 成人免费在线视频 | 好姑娘高清在线观看电影 | 欧美在线精品一区 | 亚洲精品电影网在线观看 | 亚洲淫视频 | 国产精品久久久久一区二区三区 | 欧美在线| 在线观看免费黄色片 | 奇米久久 | 国产一区二区日韩 | 日韩一区二区三区四区五区六区 | 日韩网| 国产精品久久久久久久久污网站 | 中国大陆高清aⅴ毛片 | 四虎在线观看 | 成人精品一区二区三区中文字幕 | 国产伦精品一区二区三区照片91 | 欧美日韩专区 | 亚洲网站在线 | 91精品国产一区二区在线观看 |