Java并发编程之Executor接口的使用

2022-07-23,,,,

一、executor接口的理解

  • executor属于java.util.concurrent包下;
  • executor是任务执行机制的核心接口

二、executor接口的类图结构

由类图结构可知:

  • threadpoolexecutor 继承了abstractexecutorservice接口;
  • abstractexecutorservice接口实现了executorservice接口;
  • executorservice继承了executor接口;
  • 因此以下部分主要讲解threadpoolexecutor类。

三、executor接口中常用的方法

void execute(runnable command) 在将来的某个时间执行给定的命令。 该命令可以在一个新线程,一个合并的线程中或在调用线程中执行,由executor实现。

四、线程池的创建分为两种方式(主要介绍通过threadpoolexecutor方式)

注:通过executors类的方式创建线程池,参考lz此博文链接https://www.jb51.net/article/215163.htm

1.threadpoolexecutor类中的构造方法

public threadpoolexecutor(int corepoolsize, int maximumpoolsize,long keepalivetime,timeunit unit,blockingqueue workqueue,defaulthandler)

2、 threadpoolexecutor类中构造函数的参数解析

  • corepoolsize 核心线程最大数量,通俗点来讲就是,线程池中常驻线程的最大数量
  • maximumpoolsize 线程池中运行最大线程数(包括核心线程和非核心线程)
  • keepalivetime线程池中空闲线程(仅适用于非核心线程)所能存活的最长时间
  • unit 存活时间单位,与keepalivetime搭配使用
  • workqueue 存放任务的阻塞队列
  • handler 线程池饱和策略

3、threadpoolexecutor类创建线程池示例

代码

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();
                    }
                }
            });
        }
    }
}

输出结果如下图

结论:无论是创建何种类型线程池(newfixedthreadpool、newsinglethreadexecutor、newcachedthreadpool等等),均会调用threadpoolexecutor构造函数。

到此这篇关于java并发编程之executor接口的使用的文章就介绍到这了,更多相关java executor接口内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Java并发编程之Executor接口的使用.doc》

下载本文的Word格式文档,以方便收藏与打印。