Java中线程池

本文详细介绍了Java中线程池的概念、优点和执行任务流程。线程池通过重复利用线程降低资源消耗,提高响应速度和管理线程。讨论了线程池的核心线程数、工作队列、最大线程数等参数,并列举了四种线程池类型:无界线程池、固定大小线程池、单线程池和定时调度池,适合不同场景的应用。

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

线程池在juc包下。
创建线程4种方式:继承Thread、实现Runnable、Callable、创建线程池

一:线程池优点
1.降低资源消耗:通过重复利用已创建的线程,降低线程创建与销毁带来的损耗,手动创建线程:假如线程执行结束,就会销毁线程,损耗大;
2.提高响应速度:当新任务到达时,任务不需要等待创建就可以立即执行;(线程池有空闲线程,只要有任务,就会利用这些空闲线程)
3.提高线程的可管理性:使用线程池可以统一进行线程的分配、调度与监控。(手动创建线程不知道当前有多少个线程,创建线程池有大小)。
在这里插入图片描述
二:线程池执行任务流程

在这里插入图片描述
1.首先判断核心线程池中的线程是否都在执行任务,如果是,再次查看核心线程池是否已满,如果未满,创建新的线程执行任务(即使有空闲线程,只要没满,也会创建新的线程)。如果核心线程池有空闲线程,则将任务直接分配给空闲线程执行。否则执行第二步。
2.判断工作队列(BlockingQueue)是否已满,如果工作队列没有满,将提交任务存储到工作队列等待核心池的调度,否则若工作队列已满,进行第三步。
3.判断当前线程池中的线程数量是否已将达到最大值maxiumSize,若达到最大值,将任务交给饱和策略处理,否则创建新线程执行此任务。

三.线程池的使用
1.手工创建线程池:
通过创建ThreadPoolExecutor来创建线程池

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                               RejectedExecutionHandler handler) 

参数解释:

  1. corePoolSize:核心池大小,当提交任务到线程池时,线程池会创建一个新的线程来执行任务,即使核心池有其他空闲线程也会创建新线程,一直到线程数达到核心池的最大大小。
    调用prestartAllCoreThreads()线程池会提前创建线程达到核心线程池最大值并启动所有核心线程。
  2. workQueue(工作队列):用于保存等待执行任务的阻塞队列。
    可以选择一下几个阻塞队列:
    a. ArrayBlockingQueue:基于数组结构的有界阻塞队列,此队列按照FIFO原则对元素进行排序;
    b: LinkedBlockingQueue:基于链表结构的阻塞队列,按照FIFO排序元素,吞吐量高于
    ArrayBlockingQueue,Executors.newFixedThreadPool()是固定大小线程池,采用此队列;
    c : SynchronousQueue :一个不存储元素的阻塞队列,是无界队列(不限制个数,只要有任务插入会阻塞排队)。
    每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态,吞吐量一般比LinkedBlockingQueue要高。Executors.newCachedThreadPool()采用此队列。
    d: PriorityBlockingQueue:具有优先级的无界阻塞队列(优先级队列底层是堆)。
  3. maximumPoolSize(线程池最大线程数量):线程池允许创建的最大线程数。如果队列已满并且已创建的线程数小于此参数,则线程池会再创建新的线程执行任务。否则,调用饱和策略处理。如果采用最大队列,此参数无意义。
  4. keepAliveTime(线程保持活动时间): 线程池的工作线程空闲后,保持存活的时间。若任务很多,并且每个任务执行的时间较短,可以调大此参数来提高线程利用率。
  5. TimeUnit(keepAliveTime时间单位)
  6. RejectedExecutionHandler(饱和策略):当队列和线程池都满,说明线程池处于饱和状态,此时采用饱和策略来处理任务,默认采用AborPolicy。
    JDK一共内置4个饱和策略:
    a: AbortPolicy ,表示无法处理抛出异常,JDK默认采用此策略;
    b: CallerRunsPolicy ,等待调用者线程空闲后运行此任务。比如是主线程调用调用池,当线程池空闲后,主线程会运行此任务。
    c: DiscardOldestPolicy ,丢弃阻塞队列中最近的一个任务,并执行当前任务。
    d: DiscardPolicy ,不处理,直接将新任务丢弃,也不报错。

四: 创建线程池实例:

参数是Runnable

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class Mthread implements Runnable
{
    @Override
    public void run() {
        for(int i=0;i<10;i++)
        {
            System.out.println(Thread.currentThread().getName()+"、"+i);
        }
    }
}
public class TestExecutor {
    public static void main(String[] args) {
        Mthread mthread=new Mthread();
        ExecutorService executorService=new ThreadPoolExecutor(
                3,5,2000,TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>());  //创建线程池
        for(int i=0;i<4;i++)
        {
            executorService.execute(mthread);  
            //4个线程,但是在这里核心池3个线程可以处理当前4个线程,每个线程都要执行循环10次
        }
        executorService.shutdown();
    }
}

结果如下:

pool-1-thread-1、0
pool-1-thread-3、0
pool-1-thread-2、0
pool-1-thread-3、1
pool-1-thread-1、1
pool-1-thread-3、2
pool-1-thread-2、1
pool-1-thread-3、3
pool-1-thread-1、2
pool-1-thread-3、4
pool-1-thread-2、2
pool-1-thread-3、5
pool-1-thread-1、3
pool-1-thread-3、6
pool-1-thread-2、3
pool-1-thread-3、7
pool-1-thread-1、4
pool-1-thread-3、8
pool-1-thread-2、4
pool-1-thread-3、9
pool-1-thread-1、5
pool-1-thread-1、6
pool-1-thread-2、5
pool-1-thread-1、7
pool-1-thread-3、0
pool-1-thread-1、8
pool-1-thread-2、6
pool-1-thread-1、9
pool-1-thread-3、1
pool-1-thread-2、7
pool-1-thread-3、2
pool-1-thread-2、8
pool-1-thread-3、3
pool-1-thread-2、9
pool-1-thread-3、4
pool-1-thread-3、5
pool-1-thread-3、6
pool-1-thread-3、7
pool-1-thread-3、8
pool-1-thread-3、9

对于4个线程,线程池创建了3个线程。

如果参数是Callable:

import java.util.concurrent.*;

class Mthread implements Runnable
{
    @Override
    public void run() {
        for(int i=0;i<10;i++)
        {
            System.out.println(Thread.currentThread().getName()+"、"+i);
        }
    }
}
class MCallThread implements Callable<String>
{
    @Override
    public String call() {
        for(int i=0;i<10;i++)
        {
            System.out.println(Thread.currentThread().getName()+"、"+i);
        }
        return Thread.currentThread().getName()+"执行完毕";
    }
}
public class TestExecutor {
    public static void main(String[] args) {
       MCallThread mthread=new MCallThread();
        ExecutorService executorService=new ThreadPoolExecutor(
                3,5,2000,TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>());  //创建线程池
        for(int i=0;i<4;i++)
        {
            Future<String> future=executorService.submit(mthread);
            try {
                System.out.println(future.get()); //获取返回值
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        executorService.shutdown();
    }
}
pool-1-thread-1、0
pool-1-thread-1、1
pool-1-thread-1、2
pool-1-thread-1、3
pool-1-thread-1、4
pool-1-thread-1、5
pool-1-thread-1、6
pool-1-thread-1、7
pool-1-thread-1、8
pool-1-thread-1、9
pool-1-thread-1执行完毕
pool-1-thread-2、0
pool-1-thread-2、1
pool-1-thread-2、2
pool-1-thread-2、3
pool-1-thread-2、4
pool-1-thread-2、5
pool-1-thread-2、6
pool-1-thread-2、7
pool-1-thread-2、8
pool-1-thread-2、9
pool-1-thread-2执行完毕
pool-1-thread-3、0
pool-1-thread-3、1
pool-1-thread-3、2
pool-1-thread-3、3
pool-1-thread-3、4
pool-1-thread-3、5
pool-1-thread-3、6
pool-1-thread-3、7
pool-1-thread-3、8
pool-1-thread-3、9
pool-1-thread-3执行完毕
pool-1-thread-1、0
pool-1-thread-1、1
pool-1-thread-1、2
pool-1-thread-1、3
pool-1-thread-1、4
pool-1-thread-1、5
pool-1-thread-1、6
pool-1-thread-1、7
pool-1-thread-1、8
pool-1-thread-1、9
pool-1-thread-1执行完毕

可以发现当一个线程执行完毕,才会执行另一个线程。因为FutureTask类执行任务只执行一次,并且会阻塞其他线程。Future.get( )会阻塞其他线程,一直等到当前Callable线程执行完毕拿到返回值为止。

五:JDK内置4大线程池
普通调度池:

  1. 创建无大小限制的线程池:Executors.newCachedThreadPoll( );
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

核心线程池大小为0,将线程放入无界阻塞队列中,根据线程任务快慢,调整线程数量:假如任务很快执行结束,创建线程很少,如果任务执行较长,会不断创建新线程。
适用于很多短期任务的小程序,负载较轻的服务器。

  1. 创建固定大小线程池:Executors.newFixedThreadPool(int nThreads) ,参数为线程数大小。
    适用于为了满足资源管理的需求而需要限制当前线程数量的应用场合,适用于负载较重的服务器。
public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
  1. 单线程池:Executors. newSingleThreadExecutor( );从头到尾只有一个线程执行。
    适用于需要保证顺序的执行各个任务,并且在任意时间点,不会有多个线程活动的场景。

定时调度池
Executors.newScheduledThreadPool( );

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

如:延迟执行一次

public class TestExecutor {
    public static void main(String[] args) {
        Mthread mthread = new Mthread();
        ScheduledExecutorService scheduledExecutorService =
                Executors.newScheduledThreadPool(3);
        scheduledExecutorService.schedule(mthread, 3, TimeUnit.SECONDS);//3秒后开始执行
        scheduledExecutorService.shutdown();
    }
}

3秒后会执行一次。

定时器:

public class TestExecutor {
    public static void main(String[] args) {
        Mthread mthread = new Mthread();
        ScheduledExecutorService scheduledExecutorService =
                Executors.newScheduledThreadPool(3);
        scheduledExecutorService.scheduleAtFixedRate(mthread, 3, 2,TimeUnit.SECONDS);//3秒后开始执行
        scheduledExecutorService.shutdown();
    }
}

延迟3秒每隔两秒执行一次。
可以用scheduledExecutorService.scheduleAtFixedRate( )实现定时器。

### Java 中线程池的使用方法及示例代码 Java 中的线程池主要用于管理和重用线程资源,从而提高应用程序的性能和响应速度。以下是关于线程池的具体实现方式及相关示例代码。 #### 一、线程池的核心概念 线程池的主要目的是减少每次创建新线程所带来的开销,并允许更高效地管理并发任务。核心组件包括 `Executor` 接口及其子接口 `ExecutorService`,以及具体的实现类如 `ThreadPoolExecutor` 和一些便捷工厂方法(如 `Executors.newFixedThreadPool()` 等)[^1]。 --- #### 二、常用的线程池类型及其实现 ##### 2.1 FixedThreadPool 此线程池具有固定的线程数量,超出的任务会被放入队列中等待执行。 ```java // 创建一个固定大小为3的线程池 ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); for (int i = 0; i < 5; i++) { final int taskNumber = i; fixedThreadPool.execute(() -> { System.out.println("Task " + taskNumber + " is running on thread " + Thread.currentThread().getName()); }); } fixedThreadPool.shutdown(); // 关闭线程池 ``` 这种方式适用于需要严格控制并发线程数的情况[^2]。 --- ##### 2.2 CachedThreadPool 此类线程池会根据需要动态创建新的线程,但在空闲时会回收未使用的线程。 ```java ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); for (int i = 0; i < 10; i++) { final int taskIndex = i; cachedThreadPool.submit(() -> { try { Thread.sleep(100); // 模拟耗时操作 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println("Executing Task " + taskIndex); }); } cachedThreadPool.shutdown(); ``` 适合短生命周期的小型任务场景。 --- ##### 2.3 SingleThreadExecutor 仅有一个工作线程,按顺序依次执行提交的任务。 ```java ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); singleThreadExecutor.submit(() -> System.out.println("First Task")); singleThreadExecutor.submit(() -> System.out.println("Second Task")); singleThreadExecutor.shutdown(); ``` 常用于串行化任务处理。 --- ##### 2.4 ScheduledThreadPool 能够安排命令在未来某个时刻执行,也可以周期性地重复执行某项任务。 ```java ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2); scheduledThreadPool.schedule(() -> System.out.println("Delayed Task"), 2, TimeUnit.SECONDS); scheduledThreadPool.scheduleAtFixedRate(() -> { System.out.println("Periodic Task at " + LocalDateTime.now()); }, 0, 1, TimeUnit.SECONDS); scheduledThreadPool.shutdown(); ``` 对于定时任务非常有用。 --- ##### 2.5 WorkStealingPool (JDK 1.8 新增) 利用 ForkJoinPool 技术实现的工作窃取算法,旨在最大化 CPU 利用率。 ```java ExecutorService workStealingPool = Executors.newWorkStealingPool(); IntStream.rangeClosed(1, 5).forEach(i -> { workStealingPool.submit(() -> { System.out.println("Task-" + i + " executed by " + Thread.currentThread().getName()); }); }); workStealingPool.shutdown(); ``` 推荐在高吞吐量计算密集型环境中采用。 --- #### 三、手动创建线程池 (`ThreadPoolExecutor`) 如果默认提供的几种线程池无法完全满足业务需求,则可通过 `ThreadPoolExecutor` 自定义更多细节参数。 ```java ThreadPoolExecutor customThreadPool = new ThreadPoolExecutor( 2, // 核心线程数 corePoolSize 4, // 最大线程数 maximumPoolSize 60L, // 空闲线程存活时间 keepAliveTime TimeUnit.SECONDS, // 时间单位 unit new LinkedBlockingQueue<>(100)); // 任务队列 queue customThreadPool.execute(() -> System.out.println("Custom Pool Example")); customThreadPool.shutdown(); ``` 通过调整这些参数可以灵活应对各种复杂情况。 --- ### 总结 以上分别介绍了五种典型的线程池类型及其适用范围,并提供了相应的代码片段帮助理解其基本用法。合理选用合适的线程池有助于优化系统的整体表现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值