线程池

本文深入探讨了线程池的原理,包括其体系结构、特点及如何通过控制线程数量提升系统性能。介绍了四种常见线程池的创建方式:固定大小线程池、缓存线程池、单个线程池和定时线程池,并提供了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


线程池:提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建与销毁额外开销,提高了响应的速度
线程池的工作主要是控制运行的线程的数量,处理过程中将任务放入队列,然后再线程创建后启动这些任务,如果线程数量超过了最大数量,超出数量的线程排队等候,等其他线程执行完毕,再从队列中去除任务来执行。

特点

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

  1. 降低资源消耗。通过重复利用以创建的线程降低线程创建和销毁造成的消耗。
  2. 提高响应速度。当任务到达时,任务可以不需要等到线程创建就能立即执行。
  3. 提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程可以进行统一的分配,调优和监控。

线程池的体系结构

java.util.concurrent.Executor : 负责线程的使用与调度的根接口

  •  |--**ExecutorService 子接口: 线程池的主要接口
    
  •  	|--ThreadPoolExecutor 线程池的实现类
    
  •  	|--ScheduledExecutorService 子接口:负责线程的调度
    
  •  		|--ScheduledThreadPoolExecutor :继承 ThreadPoolExecutor, 实现 ScheduledExecutorService
    

工具类 : Executors

ExecutorService.newFixedThreadPool()

创建固定大小的线程池。

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

主要特点如下:

  1. 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
  2. newFixedThreadPool创建的线程池corePoolSize和maximumPoolSize是相等的,它使用的是LinkedBlockingQueue阻塞队列.

ExecutorService newCachedThreadPool()

缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量。

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

主要特点如下:

  1. 创建一个可缓存的线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
  2. newCachedThreadPool创建的线程池corePoolSize设置为0,maximumPoolSize设置为Integer.MAX_VALUE,它使用的是SynchronousQueue同步阻塞队列,也就是说来了任务就创建线程运行,当线程空闲超过60秒,就销毁线程。

ExecutorService newSingleThreadExecutor()

创建单个线程池。线程池中只有一个线程,底层代码是调用了LinkedBlockingQueue阻塞队列

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

主要特点如下

  1. 创建一个单线程的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序执行。
  2. ewFixedThreadPool创建的线程池corePoolSize和maximumPoolSize都设置为1,它使用的是LinkedBlockingQueue阻塞队列。

ScheduledExecutorService newScheduledThreadPool()

创建固定大小的线程,可以延迟或定时的执行任务。 DelayedWorkQueue是ScheduledThreadPoolExecutor中的一个静态类,功能类似DelayQueue(使用优先级队列实现的延迟无界阻塞队列)

public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

示例代码

public class ThreadPoolExcutorDemo {
    public static void main(String[] args) {

        //ExecutorService threadPool = Executors.newFixedThreadPool(5); //一池5个处理线程
        //ExecutorService threadPool = Executors.newSingleThreadExecutor(); //一池一处理线程
        ExecutorService threadPool = Executors.newCachedThreadPool();   //一池N处理线程


       try{
           for (int i = 0; i < 10; i++) {
               threadPool.execute(() -> {
                   System.out.println(Thread.currentThread().getName());
               });

               TimeUnit.MILLISECONDS.sleep(1);
           }
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           threadPool.shutdown();
       }

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值