常见线程池创建过程以及源码分析

54 阅读2分钟

本文已参与「新人创作礼」活动, 一起开启掘金创作之路。



package com.wsx.threadPool;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}

一个cup和四个cpu

之前单核多线程 是四个线程不停切换,用一个cup

现在是四核多线程是 四个线程一个线程用一个cpu,效率变高

线程池做的工作主要是控制运行的线程的数量,处理过程中将任务放入队列,然后在线程创建后启动这些任务,如果线程数量超过了最大数量超出数量的线程排队等候,等其它线程执行完毕,再从队列中取出任务来执行。

主要特点为:线程复用: 控制最大并发数,管理线程。

第一:降低资源消耗。通过重复利用己创建的线程降低线程创建和销毁造成的消耗。

第二:提高响应速度。当任务到达时,任务可以不需要的等到线程创建就能立即执行。

第三:提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配、调优和监控

线程池如何使用脑图

架构说明

threadpoolexecutor

executors

image.png

image.png Executors.newFixedThreadPool(int) Executors.newSingle ThreadExecutor() Executors.newCachedThreadPool()

执行长期的任务,性能好很多 一个任务一个任务执行的场景 适用:执行很多短期异步的小程序或者负载较轻的服务器

底层源码都是new ThreadPoolExecutor

public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPool Executor( nThreads,nThreads,keepAliveTime: 0L,TimeUnit . MILL ISECONDS,new LinkedBlockingQueue());

主要特点如下:

1创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

2 newFixedThreadPool创建的线程池corePoolSize和maximumPoolSize值是相等的,它使用的 LinkedBlockingQueue;

Executors.newSingleThreadExecutor()

@ NotNull public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor( corePoolSize: 1,maximumPoolSize: 1, keepAliveTime: 0L,TimeUnit .MILLISECONDS , new LinkedBlockingQueue())); }

主要特点如下:

1创建 一个单线程化的线程池,它只会用唯-一的工作线程来执行任务, 保证所有任务按照指定顺序执行。

2 newSingle' ThreadExecutor将corePoolSize和maximumPoolSize都设置为1,它使用的LinkedBlockingQueue

Executors.newCachedThreadPool()

@NotNull public static ExecutorService newCachedThreadPool( ) { return new ThreadPoolExecutor( corePoolSize: 0,Integer .MAX_ VALUE , keepAliveTime: 60L,TimeUnit . SECONDS , new SynchronousQueue()); }

主要特点如下:

1创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

2 newCachedThreadPool将corePoolSize设置为0,将maximumPoolSize 设置为Integer.MAX_ _VALUE, 使用的SynchronousQueue,也就是说来了任务就创建线程运行,当线程空闲超过60秒,就销毁线程