日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Java高并发程序设计(六)--线程池(1)

發布時間:2024/1/17 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java高并发程序设计(六)--线程池(1) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

線程的創建和關閉需要花費時間,可能會浪費資源,所以可以通過讓線程復用來解決這個問題。

線程池就是這樣一個概念,當需要創建線程的時候直接從線程池中獲取,當關閉線程的時候直接歸還線程給線程池。

ThreadPoolExecutor就是JDK提供的這樣一個類。

它繼承AbstructExecutorService類,AbstructExecutorService類實現ExecutorSerive接口,ExecutorSerive接口繼承Executor接口。

具體方法可以在API中自行查看。

看一下ThreadPoolExtcutor的構造方法:

public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler) {if (corePoolSize < 0 ||maximumPoolSize <= 0 ||maximumPoolSize < corePoolSize ||keepAliveTime < 0)throw new IllegalArgumentException();if (workQueue == null || threadFactory == null || handler == null)throw new NullPointerException();this.corePoolSize = corePoolSize;this.maximumPoolSize = maximumPoolSize;this.workQueue = workQueue;this.keepAliveTime = unit.toNanos(keepAliveTime);this.threadFactory = threadFactory;this.handler = handler;}

下面是對它參數的解釋:

corePoolSize:指定了線程池中線程的數量

maximumPoolSize:指定了線程池中線程的最大數量

keepAliveTime:當線程數量超過corePoolSize,多余線程的存活時間

TimeUnit:keepAliveTime的單位

workQueue:任務隊列,被提交但還沒執行的任務

threadFactory:用于創建線程

Handler:線程太多的拒絕策略

線程池有四個構造函數,其他三個只是把一些參數變成了默認而已,然后調用的這個構造函數。

對線程池類有點基本的了解之后接下來看看另一個類Extcutors。它是一個工廠類,可以從它獲得特定功能的線程池。

public static ExecutorService newFixedThreadPool(xxxxxxx)
public static ExecutorService newSingleThreadExecutor(xxxx)?
public static ExecutorService newCachedThreadPool(xxxxx)
public static ScheduledExecutorService newSingleThreadScheduledExecutor(xxxx)
public static ScheduledExecutorService newScheduledThreadPool(xxxxx)

功能分別是獲得固定線程數目的線程池,獲得一個線程的線程池,獲得線程數量可變的線程池,獲得可在給定時間執行的單線程池,獲得可在給定時間執行的多線程池。

對于前三個來說,它們只是根據參數不同對ThreadPoolExecutor進行了封裝。

而ScheduledExecutorService則是繼承自ExecutorService,又在它的基礎上添加了一些功能。

寫個小例子:

public class demo implements Runnable{public static void main(String[] args) {ExecutorService es=Executors.newFixedThreadPool(2);for(int i=0;i<10;i++){es.submit(new Thread(new demo()));}}public void run() {System.out.println(System.currentTimeMillis());try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}} }

獲得一個數量為2的固定線程數量線程池,在run里面每個線程sleep兩秒,結果如下

可以清楚地看到每兩秒后兩個線程被執行。

線程的邏輯調度如下:

?

當線程池滿,隊列也滿的時候,會采用拒絕策略,JDK提供了四種內置拒絕策略在線程池類里面:

具體的可以自行查找相關資料。

自此告一段落,線程池還有很多內容沒有總結,后續再總結吧。

轉載于:https://www.cnblogs.com/blogofjzq/p/9405773.html

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的Java高并发程序设计(六)--线程池(1)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。