Java併發程式設計的藝術 十一 執行緒池 2

2021-08-17 05:35:04 字數 1237 閱讀 8237

任務執行器 

executor框架最核心的介面是executor,它表示任務的執行器。 

executor的子介面為executorservice。 

executorservice有兩大實現類:threadpoolexecutor和scheduledthreadpoolexecutor。

執行結果 

future介面表示非同步的執行結果,它的實現類為futuretask。

public

static executorservice newfixedthreadpool(int nthreads)

corepoolsize和maximunpoolsize都為使用者設定的執行緒數量nthreads;

keepalivetime為0,意味著一旦有多餘的空閒執行緒,就會被立即停止掉;但這裡keepalivetime無效;

阻塞佇列採用了linkedblockingqueue,它是乙個無界佇列;

由於阻塞佇列是乙個無界佇列,因此永遠不可能拒絕任務;

由於採用了無界佇列,實際執行緒數量將永遠維持在nthreads,因此maximumpoolsize和keepalivetime將無效。

public

static executorservice newcachedthreadpool()

它比較適合處理執行時間比較小的任務;

corepoolsize為0,maximumpoolsize為無限大,意味著執行緒數量可以無限大;

keepalivetime為60s,意味著執行緒空閒時間超過60s就會被殺死;

採用synchronousqueue裝等待的任務,這個阻塞佇列沒有儲存空間,這意味著只要有請求到來,就必須要找到一條工作執行緒處理他,如果當前沒有空閒的執行緒,那麼就會再建立一條新的執行緒。

public

static executorservice newsinglethreadexecutor()

採用的阻塞隊列為linkedblockingqueue;

scheduledatfixedrate

scheduledwithfixeddelay

schduledfuturetask接收的引數:

time:任務開始的時間

sequencenumber:任務的序號

period:任務執行的時間間隔

它採用delayqueue儲存等待的任務

工作執行緒的執行過程:

Java併發程式設計的藝術 十二 執行緒安全

讀執行緒 thread t1 new thread new runnable start 寫執行緒 thread t2 new thread new runnable start 寫執行緒 thread t2 new thread new runnable public void run synch...

Java併發程式設計的藝術 十二 執行緒安全

讀執行緒 thread t1 new thread new runnable start 寫執行緒 thread t2 new thread new runnable start 寫執行緒 thread t2 new thread new runnable public void run synch...

Java併發程式設計的藝術 筆記

併發存在的問題 上下文切換耗時,死鎖,軟硬體資源限制 解決方法 減少上下文切換 1.無鎖併發程式設計 讓不同的執行緒處理不同的資料段 將資料id採用hash演算法分配給不同的執行緒 2.cas演算法 compare and set使用jni 3.使用最少執行緒 減少處於waiting狀態的執行緒 j...