Java并發(fā)編程之Executor接口的使用

由類圖結(jié)構(gòu)可知:
ThreadPoolExecutor 繼承了AbstractExecutorService接口; AbstractExecutorService接口實(shí)現(xiàn)了ExecutorService接口; ExecutorService繼承了Executor接口; 因此以下部分主要講解ThreadPoolExecutor類。三、Executor接口中常用的方法void execute(Runnable command) 在將來的某個(gè)時(shí)間執(zhí)行給定的命令。 該命令可以在一個(gè)新線程,一個(gè)合并的線程中或在調(diào)用線程中執(zhí)行,由Executor實(shí)現(xiàn)。
四、線程池的創(chuàng)建分為兩種方式(主要介紹通過ThreadPoolExecutor方式)注:通過Executors類的方式創(chuàng)建線程池,參考lz此博文鏈接https://www.jb51.net/article/215163.htm
1.ThreadPoolExecutor類中的構(gòu)造方法
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue workQueue,defaultHandler)
2、 ThreadPoolExecutor類中構(gòu)造函數(shù)的參數(shù)解析
corePoolSize 核心線程最大數(shù)量,通俗點(diǎn)來講就是,線程池中常駐線程的最大數(shù)量 maximumPoolSize 線程池中運(yùn)行最大線程數(shù)(包括核心線程和非核心線程) keepAliveTime線程池中空閑線程(僅適用于非核心線程)所能存活的最長(zhǎng)時(shí)間 unit 存活時(shí)間單位,與keepAliveTime搭配使用 workQueue 存放任務(wù)的阻塞隊(duì)列 handler 線程池飽和策略3、ThreadPoolExecutor類創(chuàng)建線程池示例
代碼
package com.xz.thread.executor;import java.util.concurrent.*;/** * @description: * @author: xz * @create: 2021-06-16 22:16 */public class Demo { public static void main(String[] args) {ThreadPoolExecutor pool = new ThreadPoolExecutor(3,3,1L, TimeUnit.MINUTES,new LinkedBlockingDeque<>());for(int i=1;i<=5;i++){ pool.execute(new Runnable() {@Overridepublic void run() { System.out.println(Thread.currentThread().getName()); try {Thread.sleep(1000);System.out.println('睡眠一秒鐘'); } catch (InterruptedException e) {e.printStackTrace(); }} });} }}
輸出結(jié)果如下圖

結(jié)論:無論是創(chuàng)建何種類型線程池(newFixedThreadPool、newSingleThreadExecutor、newCachedThreadPool等等),均會(huì)調(diào)用ThreadPoolExecutor構(gòu)造函數(shù)。


到此這篇關(guān)于Java并發(fā)編程之Executor接口的使用的文章就介紹到這了,更多相關(guān)Java Executor接口內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 理解PHP5中static和const關(guān)鍵字2. IntelliJ IDEA安裝插件的方法步驟3. php模擬實(shí)現(xiàn)斗地主發(fā)牌4. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟5. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)6. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼7. Vuex localStorage的具體使用8. vue 使用localstorage實(shí)現(xiàn)面包屑的操作9. spring acegi security 1.0.0 發(fā)布10. MyBatis中的JdbcType映射使用詳解

網(wǎng)公網(wǎng)安備