ThreadPoolExecutor原始碼分析

2021-08-27 22:23:31 字數 2179 閱讀 7711

1. 建構函式

public threadpoolexecutor(int corepoolsize,

int maximumpoolsize,

long keepalivetime,

timeunit unit,

blockingqueueworkqueue)

它最終呼叫另外乙個建構函式

public threadpoolexecutor(int corepoolsize,

int maximumpoolsize,

long keepalivetime,

timeunit unit,

blockingqueueworkqueue,

threadfactory threadfactory,

rejectedexecutionhandler handler)

建構函式主要完成一些初始化的工作,如工作執行緒數目,保持有效時間,等待佇列等。

2.execute()方法分析

public void execute(runnable command)

if (isrunning(c) && workqueue.offer(command))

else if (!addworker(command, false))

reject(command);

}

在**註解中說明很清楚,它有兩個重要的操作:加入佇列或者拒絕。

3.工作執行緒

工作執行緒(worker)主要是來執行使用者任務的,它的run方法如下:

/** delegates main run loop to outer runworker */

public void run()

再看看runworker的實現。

final void runworker(worker w) catch (runtimeexception x) catch (error x) catch (throwable x) finally

} finally

}completedabruptly = false;

} finally

}

有幾點注意:

1. beforeexecute(wt, task),afterexecute(task, thrown);是沒有實現的,使用者可以擴充套件;

2. task.run(),這裡不是start()方法。

4.一道被無數面試官問的問題:shutdown()

執行緒池shutdown()方法,並不是馬上關閉。看看jdk官方文件是如何描述的。

/*** initiates an orderly shutdown in which previously submitted

* tasks are executed, but no new tasks will be accepted.

*/

它不會再接受新的執行緒加入,否則會丟擲regjectexception。但是它不會馬上退出,直到之前

加入的執行緒執行完成之後才會退出。

另外乙個方法shutdownnow()也不能馬上關閉執行緒池,也還是看看jdk官方的描述吧。

/*** attempts to stop all actively executing tasks, halts the

* processing of waiting tasks, and returns a list of the tasks

* that were awaiting execution. these tasks are drained (removed)

* from the task queue upon return from this method.

*/

看到attempts沒,只是盡力,並不保證。它與shutdown()的區別是,它有返回值,並且它們設定的狀態不一樣,乙個是shutdown,另乙個是stop。

Cartographer原始碼篇 原始碼分析 1

在安裝編譯cartographer 1.0.0的時候,我們可以看到 主要包括cartorgarpher ros cartographer ceres sover三個部分。其中,ceres solver用於非線性優化,求解最小二乘問題 cartographer ros為ros平台的封裝,獲取感測器資料...

AbstractListView原始碼分析3

normal list that does not indicate choices public static final int choice mode none 0 the list allows up to one choice public static final int choice ...

Android AsyncTask原始碼分析

android中只能在主線程中進行ui操作,如果是其它子執行緒,需要借助非同步訊息處理機制handler。除此之外,還有個非常方便的asynctask類,這個類內部封裝了handler和執行緒池。本文先簡要介紹asynctask的用法,然後分析具體實現。asynctask是乙個抽象類,我們需要建立子...