jdk1 8執行緒池 基於原始碼了解工作流程

2021-10-06 15:27:44 字數 2237 閱讀 3945

構造方法

public

threadpoolexecutor

(int corepoolsize,

int maximumpoolsize,

long keepalivetime,

timeunit unit,

blockingqueue

workqueue,

threadfactory threadfactory,

rejectedexecutionhandler handler)

核心處理方法

public

void

execute

(runnable command)

// 當前執行緒數量大於核心執行緒數量if(

isrunning

(c)&& workqueue.

offer

(command)

)// 佇列滿了

elseif(

!addworker

(command,

false))

// 新建執行緒執行(執行緒數量邊界為 maximumpoolsize)

reject

(command)

;// 執行緒數量達到 maximumpoolsize, 等待佇列滿了,執行拒絕策略

}

addworker(runnable firsttask, boolean core)

private

boolean

addworker

(runnable firsttask,

boolean core)

}boolean workerstarted =

false

;boolean workeradded =

false

; worker w = null;

try}

finally

if(workeradded)}}

finally

return workerstarted;

}

worker

private

final

class

worker

extends

abstractqueuedsynchronizer

implements

runnable

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

public

void

run(

)

runworker(worker w)

final

void

runworker

(worker w)

catch

(runtimeexception x)

catch

(error x)

catch

(throwable x)

finally

}finally

} completedabruptly =

false;}

finally

}

gettask()

private runnable gettask()

int wc =

workercountof

(c);

// are workers subject to culling?

boolean timed = allowcorethreadtimeout || wc > corepoolsize;

// 根據是否允許核心執行緒死亡或者當前執行緒數大於了核心執行緒數if(

(wc > maximumpoolsize ||

(timed && timedout))&&

(wc >

1|| workqueue.

isempty()

))trycatch

(interruptedexception retry)

}}

執行緒池原理 JDK1 8原始碼解析

執行緒池建立的方式 public threadpoolexecutor int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,blockingqueueworkqueue,rejectedexecutionhand...

HashMap原始碼分析 基於jdk1 8

初始化 描述 hashmap構造方法一公共有4個,分別如下 無參構造 public hashmap 給定初始容量 param initialcapacity public hashmap int initialcapacity 指定初始容量和載入因子 param initialcapacity pa...

Stack原始碼解析 基於JDK1 8

總結public class stack extends vector stack繼承自vector,所以是執行緒安全的。public synchronized e pop public synchronized e peek public e push e item public synchron...