Java并發(fā)編程之Executor接口的使用
一、Executor接口的理解
- Executor屬于java.util.concurrent包下;
- Executor是任務(wù)執(zhí)行機(jī)制的核心接口;
二、Executor接口的類圖結(jié)構(gòu)

由類圖結(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此博文鏈接http://www.dhdzp.com/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線程池中空閑線程(僅適用于非核心線程)所能存活的最長時(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() {
@Override
public 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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot中使用Redis對接口進(jìn)行限流的實(shí)現(xiàn)
本文將結(jié)合實(shí)例代碼,介紹SpringBoot中使用Redis對接口進(jìn)行限流的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07
RestTemplate調(diào)用POST和GET請求示例詳解
這篇文章主要為大家介紹了RestTemplate調(diào)用POST和GET請求示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
javaCV開發(fā)詳解之推流器和錄制器的實(shí)現(xiàn)
這篇文章主要介紹了javaCV開發(fā)詳解之推流器和錄制器實(shí)現(xiàn),對JavaCV感興趣的同學(xué),可以參考下2021-04-04
java基于線程池和反射機(jī)制實(shí)現(xiàn)定時(shí)任務(wù)完整實(shí)例
這篇文章主要介紹了java基于線程池和反射機(jī)制實(shí)現(xiàn)定時(shí)任務(wù)的方法,以完整實(shí)例形式較為詳細(xì)的分析了Java定時(shí)任務(wù)的功能原理與實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
SpringBoot基于Sentinel在服務(wù)上實(shí)現(xiàn)接口限流
這篇文章主要介紹了SpringBoot基于Sentinel在服務(wù)上實(shí)現(xiàn)接口限流,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
springboot前端傳參date類型后臺(tái)處理的方式
這篇文章主要介紹了springboot前端傳參date類型后臺(tái)處理的方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07

