Java并發(fā)編程之Executor接口的使用
由類圖結(jié)構(gòu)可知:
ThreadPoolExecutor 繼承了AbstractExecutorService接口; AbstractExecutorService接口實現(xiàn)了ExecutorService接口; ExecutorService繼承了Executor接口; 因此以下部分主要講解ThreadPoolExecutor類。三、Executor接口中常用的方法void execute(Runnable command) 在將來的某個時間執(zhí)行給定的命令。 該命令可以在一個新線程,一個合并的線程中或在調(diào)用線程中執(zhí)行,由Executor實現(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ù)量,通俗點來講就是,線程池中常駐線程的最大數(shù)量 maximumPoolSize 線程池中運行最大線程數(shù)(包括核心線程和非核心線程) keepAliveTime線程池中空閑線程(僅適用于非核心線程)所能存活的最長時間 unit 存活時間單位,與keepAliveTime搭配使用 workQueue 存放任務(wù)的阻塞隊列 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等等),均會調(diào)用ThreadPoolExecutor構(gòu)造函數(shù)。
到此這篇關(guān)于Java并發(fā)編程之Executor接口的使用的文章就介紹到這了,更多相關(guān)Java Executor接口內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
