JAVA ThreadPoolExecutor线程池

多线程开发规范

使用 Thread 类 和 Runable 接口,可以实现多线程

但是,在阿里巴巴开发手册中,不允许使用这种方法,说法如下:

线程池

https://www.malaoshi.top/show_1EF4sk05Bq0j.html

创建对象的方式

使用 ThreadPoolExecutor 或 Executors

注意:阿里巴巴开发手册中,明确指出,不能用 Executors 创建对象

ThreadPoolExecutor

接口 java.util.concurrent.ExecutorService 是Java中对线程池定义的一个接口

ThreadPoolExecutor 实现 ExecutorService 接口,用于创建线程池

构造方法

//所有线程池最终都是通过这个方法来创建的
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)
参数:
  • corePoolSize:核心线程数,详见 链接

  • maximumPoolSize:最大线程数,详见 链接

  • keepAliveTime:空闲线程的存活时间。详见 链接

  • unit:表示keepAliveTime的单位

  • workQueue:任务队列,当核心线程数达到最大时,新任务会放在队列中排队等待执行。详见 链接

  • threadFactory:线程工厂,自定义线程的名字,daemon,优先级等,一般为:Executors.defaultThreadFactory(),也是默认值

  • handler:拒绝策略,详见 链接

执行流程

例子

简单使用例子

package ThreadPool;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Instance1_2 {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                1,
                1,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue(1),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        threadPoolExecutor.execute(new MyRun("1"));

        threadPoolExecutor.shutdown();
    }
    static class MyRun implements Runnable {
        String name;

        public MyRun(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println(name+"--开始");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(name+"--结束");
        }
    }
}

参数设置

这里只是一般参数设置,具体还需要根据环境进行测试

ThreadPoolExecutor pool = new ThreadPoolExecutor(100, 100,
        60L, TimeUnit.SECONDS,
        new LinkedBlockingQueue<Runnable>(200));

图来自:
https://blog.csdn.net/zyzzxycj/article/details/90290176

感谢:
https://blog.csdn.net/weixin_43453386/article/details/88661622


原文出处:/show_1EF4skAs2E7o.html