Java執行緒池異常處理原理

2021-09-11 03:53:38 字數 1189 閱讀 9675

executorservice exec = executors.newfixedthreadpool(8);
以上述**為例,得到executorservice例項後,我們可以通過兩種方式提交任務(runnable):

exec.execute(runnable) 和 exec.submit(runnable)

exec.submit(runnable) 實際是呼叫abstractexecutorservice.submit(runnable),將runnable包裝為乙個runnablefuture物件,這個物件實際上是futuretask例項,然後將這個futuretask交給execute方法執行。

public abstract class abstractexecutorservice implements executorservice 

protected runnablefuturenewtaskfor(runnable runnable, t value)

}

execute(ftask)會呼叫futuretask的run()方法

public class futuretaskimplements runnablefuture catch (throwable ex) 

if (ran)

set(result);

}} finally

}public v get() throws interruptedexception, executionexception

private v report(int s) throws executionexception

}

futuretask的run方法中,呼叫了callable物件的call方法,也就呼叫了我們傳入的runnable物件的run方法。可以看到,如果**(runnable)丟擲異常,會**獲並且通過setexception(ex)方法把這個異常儲存下來。

futuretask的get方法中,會將儲存的異常重新丟擲。所以,在使用submit方法提交任務的時候,利用返回的future物件的get方法可以得到任務執行中丟擲的異常,然後針對異常做一些處理。

結論:使用executorservice.submit執行任務,利用返回的future物件的get方法接收丟擲的異常,然後進行處理

java 執行緒池 異常 處理 機制 分析

public class threadtest success trycatch exception e 上述 只有在呼叫get 時丟擲異常,否則不列印任何異常資訊,檢視原始碼得到原因如下 public futuresubmit runnable task,v result executorcomp...

解析Java執行緒池的異常處理機制

今天小夥伴遇到個小問題,執行緒池提交的任務如果沒有catch異常,那麼會拋到 去,之前倒是沒研究過,本著實事求是的原則,看了一下 考慮下面這段 有什麼區別呢?你可以猜猜會不會有異常打出呢?如果打出來的話是在 executorservice threadpool executors.newfixedt...

Java執行緒池實現原理

threadpoolexecutor是jdk提供的執行緒池實現,threadpoolexector實現了execturo介面,可以自動幫助使用者建立,銷毀和保護執行緒,先來看一下最基本的使用方式 建立乙個執行緒池final executor executor new threadpoolexecut...