Execute與Submit
這兩個方法都是向線程池提交任務時要調用的方法,那麼這兩個方法到底有什麼區別呢?
線程池execute方法源碼分析
public void execute(Runnable command) {
// 判空處理
if (command == null)
throw new NullPointerException();
// 獲取當前線程數
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
// 創建失敗,再次獲取線程數目
c = ctl.get();
}
// 當前線程數>=核心線程數或者創建線程失敗
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// 添加入隊列失敗,創建新線程執行(大於最大線程數時不會創建成功)
else if (!addWorker(command, false))
reject(command);
}
- 首先進行參數判斷,爲null則拋出空指針異常。
- 判斷當前線程數是否小於核心線程數量?如果是調用addWorker方法。
- 當前線程數大於核心線程數量:然後將當前任務放入阻塞隊列中。
- 核心和隊列都滿了,創建一個非核心的線程去執行,如果滿了則執行拒絕策略。
線程池submit方法源碼分析
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
本質上也是調用的execute方法,但會將傳進來的Runnable task做一次封裝,變成一個RunnableFuture對象使得這個方法可以返回一個Future對象,最終通過Future類的get方法可以獲得返回值。