Java線程池ThreadPoolExecutor的使用

Java線程池ThreadPoolExecutor的使用

Java線程池ThreadPoolExecutor的使用

ThreadPoolExecutor就是我們用來實現線程的一個執行器,它實現了Excutor和ExecutorService接口。Excutor接口只定義了一個方法就是execute用來執行任務。ExecutorService繼承於Excutor並添加了一些其他的執行任務的方法和管理線程池的方法。

Java線程池ThreadPoolExecutor的使用

ThreadPoolExecutor繼承關係

自己通過ThreadPoolExecutor創建一個ExecutorService實例

創建ThreadPoolExecutor的實例需要7個參數,分別如下:

①、corePoolSize:核心線程數,線程池中的線程數量

②、maximumPoolSize: 線程池中最大的線程數,

③、keepAliveTime: 大於核心數的線程,空閒的時間

④、TimeUnit: keepAliveTime的時間單元

⑤、workQueue:工作隊列,大於核心線程數的任務加入工作隊列

⑥、threadFactory:創建線程的工廠類,如果需要可以自己實現

⑦、RejectedExecutionHandler:當任務數大於最大線程數並且隊列已滿時,採用的拒絕策略

Java線程池ThreadPoolExecutor的使用

ThreadPoolExecutor構造方法

Java線程池ThreadPoolExecutor的使用

創建ThreadPoolExecutor測試


使用工具類Executors創建線程池,

這個工具類提供了很多創建線程池的方法,也提供了多種類型的線程池,下圖是所有的方法,並提供了幾種ThreadFactory的實現。

Java線程池ThreadPoolExecutor的使用

Executors方法

Java線程池ThreadPoolExecutor的使用

幾種常用線程池


分享到:


相關文章: