僅被調用一次,不直接執行任務,而是設定 shouldRun=true 並 notify() 喚醒 run() 循環中的執行緒。
while (true) {
synchronized(this) {
if (!shouldRun && !shouldTerminate) wait();
}
if (shouldTerminate) break;
try {
if (noThData) { // 首次初始化線程數據
if (toRun != null) {
Object[] thData = toRun.getInitData();
t.setThreadData(p, thData);
}
noThData = false;
}
if (shouldRun) {
if (toRun != null) toRun.runIt(t.getThreadData(p));
else if (toRunRunnable != null) toRunRunnable.run();
}
} catch (Throwable t) {
shouldTerminate = true; shouldRun = false;
p.notifyThreadEnd(this);
} finally {
if (shouldRun) { shouldRun = false; p.returnController(this); }
}
if (shouldTerminate) break;
}
關鍵點:getInitData() 提供線程初始化數據,runIt(Object[]) 承載實際業務邏輯;異常導致線程終止並從池移除;finally 確保線程歸還池中。
threadStart()/threadEnd() 監聽線程創建銷毀。ThreadLocal 但效率更高的線程屬性存儲(setNote/getNote),透過 control 物件防止非信任代碼篡改。getInitData()、runIt(Object[]) 兩方法。initEndpoint():建立 ServerSocket(默認 8080),設定超時。startEndpoint():啟動線程池,創建 TcpWorkerThread 監聽線程,tp.runIt(listener) 投遞任務。TcpConnection 緩存(SimplePool)。getInitData():返回 HTTP 處理器初始化數據及連接對象。runIt(Object[]) 核心流程:
acceptSocket() 阻塞等待連接。endpoint.tp.runIt(this)),實現「一線程一連接、接力監聽」。TcpConnection,設定 Socket 選項。ConnectionHandler.processConnection() 解析 Socket 流為 Request 對象,交由容器處理。finally 回收 TcpConnection 至緩存。ThreadPoolRunnable)。ControlRunnable、ThreadWithAttributes、ThreadPoolListener 解耦管理與業務。