线程池相关→ThreadPoolUtils

本文介绍了一个实用的线程池工具类,支持多种类型的线程池创建与管理,包括固定线程池、缓存线程池和单一线程池等。提供了丰富的API用于任务提交、调度以及线程池的状态控制。
   
  import android.support.annotation.IntDef;
   
  import java.lang.annotation.Retention;
  import java.lang.annotation.RetentionPolicy;
  import java.util.Collection;
  import java.util.List;
  import java.util.concurrent.Callable;
  import java.util.concurrent.ExecutionException;
  import java.util.concurrent.ExecutorService;
  import java.util.concurrent.Executors;
  import java.util.concurrent.Future;
  import java.util.concurrent.ScheduledExecutorService;
  import java.util.concurrent.ScheduledFuture;
  import java.util.concurrent.TimeUnit;
  import java.util.concurrent.TimeoutException;
   
  /**
  * <pre>
  * author: Blankj
  * blog : http://blankj.com
  * time : 2016/8/25
  * desc : 线程池相关工具类
  * </pre>
  */
  public final class ThreadPoolUtils {
   
  private ThreadPoolUtils() {
  throw new UnsupportedOperationException("u can't instantiate me...");
  }
   
  public static final int FixedThread = 0;
  public static final int CachedThread = 1;
  public static final int SingleThread = 2;
   
  @IntDef({FixedThread, CachedThread, SingleThread})
  @Retention(RetentionPolicy.SOURCE)
  public @interface Type {
  }
   
  private ExecutorService exec;
  private ScheduledExecutorService scheduleExec;
   
  /**
  * ThreadPoolUtils构造函数
  *
  * @param type 线程池类型
  * @param corePoolSize 只对Fixed和Scheduled线程池起效
  */
  public ThreadPoolUtils(@Type int type, int corePoolSize) {
  // 构造有定时功能的线程池
  // ThreadPoolExecutor(corePoolSize, Integer.MAX_VALUE, 10L, TimeUnit.MILLISECONDS, new BlockingQueue<Runnable>)
  scheduleExec = Executors.newScheduledThreadPool(corePoolSize);
  switch (type) {
  case FixedThread:
  // 构造一个固定线程数目的线程池
  // ThreadPoolExecutor(corePoolSize, corePoolSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
  exec = Executors.newFixedThreadPool(corePoolSize);
  break;
  case SingleThread:
  // 构造一个只支持一个线程的线程池,相当于newFixedThreadPool(1)
  // ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())
  exec = Executors.newSingleThreadExecutor();
  break;
  case CachedThread:
  // 构造一个缓冲功能的线程池
  // ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
  exec = Executors.newCachedThreadPool();
  break;
  }
  }
   
  /**
  * 在未来某个时间执行给定的命令
  * <p>该命令可能在新的线程、已入池的线程或者正调用的线程中执行,这由 Executor 实现决定。</p>
  *
  * @param command 命令
  */
  public void execute(Runnable command) {
  exec.execute(command);
  }
   
  /**
  * 在未来某个时间执行给定的命令链表
  * <p>该命令可能在新的线程、已入池的线程或者正调用的线程中执行,这由 Executor 实现决定。</p>
  *
  * @param commands 命令链表
  */
  public void execute(List<Runnable> commands) {
  for (Runnable command : commands) {
  exec.execute(command);
  }
  }
   
  /**
  * 待以前提交的任务执行完毕后关闭线程池
  * <p>启动一次顺序关闭,执行以前提交的任务,但不接受新任务。
  * 如果已经关闭,则调用没有作用。</p>
  */
  public void shutDown() {
  exec.shutdown();
  }
   
  /**
  * 试图停止所有正在执行的活动任务
  * <p>试图停止所有正在执行的活动任务,暂停处理正在等待的任务,并返回等待执行的任务列表。</p>
  * <p>无法保证能够停止正在处理的活动执行任务,但是会尽力尝试。</p>
  *
  * @return 等待执行的任务的列表
  */
  public List<Runnable> shutDownNow() {
  return exec.shutdownNow();
  }
   
  /**
  * 判断线程池是否已关闭
  *
  * @return {@code true}: 是<br>{@code false}: 否
  */
  public boolean isShutDown() {
  return exec.isShutdown();
  }
   
  /**
  * 关闭线程池后判断所有任务是否都已完成
  * <p>注意,除非首先调用 shutdown 或 shutdownNow,否则 isTerminated 永不为 true。</p>
  *
  * @return {@code true}: 是<br>{@code false}: 否
  */
  public boolean isTerminated() {
  return exec.isTerminated();
  }
   
   
  /**
  * 请求关闭、发生超时或者当前线程中断
  * <p>无论哪一个首先发生之后,都将导致阻塞,直到所有任务完成执行。</p>
  *
  * @param timeout 最长等待时间
  * @param unit 时间单位
  * @return {@code true}: 请求成功<br>{@code false}: 请求超时
  * @throws InterruptedException 终端异常
  */
  public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
  return exec.awaitTermination(timeout, unit);
  }
   
  /**
  * 提交一个Callable任务用于执行
  * <p>如果想立即阻塞任务的等待,则可以使用{@code result = exec.submit(aCallable).get();}形式的构造。</p>
  *
  * @param task 任务
  * @param <T> 泛型
  * @return 表示任务等待完成的Future, 该Future的{@code get}方法在成功完成时将会返回该任务的结果。
  */
  public <T> Future<T> submit(Callable<T> task) {
  return exec.submit(task);
  }
   
  /**
  * 提交一个Runnable任务用于执行
  *
  * @param task 任务
  * @param result 返回的结果
  * @param <T> 泛型
  * @return 表示任务等待完成的Future, 该Future的{@code get}方法在成功完成时将会返回该任务的结果。
  */
  public <T> Future<T> submit(Runnable task, T result) {
  return exec.submit(task, result);
  }
   
  /**
  * 提交一个Runnable任务用于执行
  *
  * @param task 任务
  * @return 表示任务等待完成的Future, 该Future的{@code get}方法在成功完成时将会返回null结果。
  */
  public Future<?> submit(Runnable task) {
  return exec.submit(task);
  }
   
  /**
  * 执行给定的任务
  * <p>当所有任务完成时,返回保持任务状态和结果的Future列表。
  * 返回列表的所有元素的{@link Future#isDone}为{@code true}。
  * 注意,可以正常地或通过抛出异常来终止已完成任务。
  * 如果正在进行此操作时修改了给定的 collection,则此方法的结果是不确定的。</p>
  *
  * @param tasks 任务集合
  * @param <T> 泛型
  * @return 表示任务的 Future 列表,列表顺序与给定任务列表的迭代器所生成的顺序相同,每个任务都已完成。
  * @throws InterruptedException 如果等待时发生中断,在这种情况下取消尚未完成的任务。
  */
  public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
  return exec.invokeAll(tasks);
  }
   
  /**
  * 执行给定的任务
  * <p>当所有任务完成或超时期满时(无论哪个首先发生),返回保持任务状态和结果的Future列表。
  * 返回列表的所有元素的{@link Future#isDone}为{@code true}。
  * 一旦返回后,即取消尚未完成的任务。
  * 注意,可以正常地或通过抛出异常来终止已完成任务。
  * 如果此操作正在进行时修改了给定的 collection,则此方法的结果是不确定的。</p>
  *
  * @param tasks 任务集合
  * @param timeout 最长等待时间
  * @param unit 时间单位
  * @param <T> 泛型
  * @return 表示任务的 Future 列表,列表顺序与给定任务列表的迭代器所生成的顺序相同。如果操作未超时,则已完成所有任务。如果确实超时了,则某些任务尚未完成。
  * @throws InterruptedException 如果等待时发生中断,在这种情况下取消尚未完成的任务
  */
  public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws
  InterruptedException {
  return exec.invokeAll(tasks, timeout, unit);
  }
   
  /**
  * 执行给定的任务
  * <p>如果某个任务已成功完成(也就是未抛出异常),则返回其结果。
  * 一旦正常或异常返回后,则取消尚未完成的任务。
  * 如果此操作正在进行时修改了给定的collection,则此方法的结果是不确定的。</p>
  *
  * @param tasks 任务集合
  * @param <T> 泛型
  * @return 某个任务返回的结果
  * @throws InterruptedException 如果等待时发生中断
  * @throws ExecutionException 如果没有任务成功完成
  */
  public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
  return exec.invokeAny(tasks);
  }
   
  /**
  * 执行给定的任务
  * <p>如果在给定的超时期满前某个任务已成功完成(也就是未抛出异常),则返回其结果。
  * 一旦正常或异常返回后,则取消尚未完成的任务。
  * 如果此操作正在进行时修改了给定的collection,则此方法的结果是不确定的。</p>
  *
  * @param tasks 任务集合
  * @param timeout 最长等待时间
  * @param unit 时间单位
  * @param <T> 泛型
  * @return 某个任务返回的结果
  * @throws InterruptedException 如果等待时发生中断
  * @throws ExecutionException 如果没有任务成功完成
  * @throws TimeoutException 如果在所有任务成功完成之前给定的超时期满
  */
  public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws
  InterruptedException, ExecutionException, TimeoutException {
  return exec.invokeAny(tasks, timeout, unit);
  }
   
  /**
  * 延迟执行Runnable命令
  *
  * @param command 命令
  * @param delay 延迟时间
  * @param unit 单位
  * @return 表示挂起任务完成的ScheduledFuture,并且其{@code get()}方法在完成后将返回{@code null}
  */
  public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
  return scheduleExec.schedule(command, delay, unit);
  }
   
  /**
  * 延迟执行Callable命令
  *
  * @param callable 命令
  * @param delay 延迟时间
  * @param unit 时间单位
  * @param <V> 泛型
  * @return 可用于提取结果或取消的ScheduledFuture
  */
  public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
  return scheduleExec.schedule(callable, delay, unit);
  }
   
  /**
  * 延迟并循环执行命令
  *
  * @param command 命令
  * @param initialDelay 首次执行的延迟时间
  * @param period 连续执行之间的周期
  * @param unit 时间单位
  * @return 表示挂起任务完成的ScheduledFuture,并且其{@code get()}方法在取消后将抛出异常
  */
  public ScheduledFuture<?> scheduleWithFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
  return scheduleExec.scheduleAtFixedRate(command, initialDelay, period, unit);
  }
   
  /**
  * 延迟并以固定休息时间循环执行命令
  *
  * @param command 命令
  * @param initialDelay 首次执行的延迟时间
  * @param delay 每一次执行终止和下一次执行开始之间的延迟
  * @param unit 时间单位
  * @return 表示挂起任务完成的ScheduledFuture,并且其{@code get()}方法在取消后将抛出异常
  */
  public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
  return scheduleExec.scheduleWithFixedDelay(command, initialDelay, delay, unit);
  }
  }
### 线程池相关面试题解析 线程池是一种用于管理和复用线程的技术,旨在提高程序性能和资源利用率。以下是与线程池相关的常见面试题及其解答。 #### 1. 什么是线程池?为什么要使用线程池线程池是一组预先创建的可重用线程集合,这些线程由线程池统一管理,包括线程的创建、销毁以及任务调度等[^2]。 使用线程池的原因在于:频繁地创建和销毁线程会带来较大的系统开销,尤其是在高并发场景下可能导致性能下降或资源耗尽。通过复用已有的线程,线程池可以有效降低这种开销,并提升系统的响应速度和稳定性[^2]。 #### 2. 线程池的核心组件有哪些? 线程池的主要组成部分包括: - **核心线程数(corePoolSize)**:线程池中始终保持活跃的最小线程数量。 - **最大线程数(maximumPoolSize)**:线程池允许的最大线程数量。 - **任务队列(workQueue)**:用于存储等待执行的任务。 - **保持存活时间(keepAliveTime)**:当线程数超过核心线程数时,多余线程的空闲生存时间。 - **拒绝策略(RejectedExecutionHandler)**:当线程池无法继续接收新任务时所采用的处理方式[^1]。 #### 3. 什么是任务队列?它的作用是什么? 任务队列是线程池中用于暂存待执行任务的数据结构。在线程池中的线程忙碌时,新提交的任务会被放入任务队列中排队等待执行。任务队列的作用主要包括: - 缓冲任务请求,平滑突发流量。 - 控制任务提交速率与线程池处理能力之间的关系。 常见的任务队列类型有无界队列(如 `LinkedBlockingQueue`)、有界队列(如 `ArrayBlockingQueue`)和同步移交队列(如 `SynchronousQueue`)[^1]。 #### 4. 线程池有哪些常见的拒绝策略? Java 中提供了多种内置的拒绝策略,具体如下: - **AbortPolicy**:直接抛出异常,阻止系统正常运行。 - **CallerRunsPolicy**:由调用方线程执行该任务,从而降低提交任务的速度。 - **DiscardOldestPolicy**:丢弃最早进入队列的任务,尝试重新提交当前任务。 - **DiscardPolicy**:静默丢弃无法处理的任务,不作任何处理。 #### 5. Java 中常用的线程池实现有哪些? Java 提供了以下几种常用线程池实现: - **FixedThreadPool**:固定大小的线程池,适用于负载较稳定的场景。 - **CachedThreadPool**:可根据需要创建新线程的缓存线程池,适合执行大量短生命周期的任务。 - **SingleThreadExecutor**:仅有一个工作线程的线程池,确保所有任务按顺序串行执行。 - **ScheduledThreadPool**:支持定时和周期性任务调度的线程池[^1]。 #### 6. 如何合理配置线程池参数? 合理的线程池参数配置需考虑以下几个方面: - **CPU 密集型任务**:线程数通常设置为 CPU 核心数 + 1,以充分利用硬件资源。 - **IO 密集型任务**:由于 IO 操作会导致线程阻塞,建议增加线程数以弥补阻塞带来的效率损失。 - **任务队列容量**:根据业务需求设定合适大小,过大可能导致内存占用过高,过小则容易触发拒绝策略。 --- ### 示例代码:自定义线程池 以下是一个简单示例,演示如何通过 `Executors` 创建不同类型的线程池: ```java import java.util.concurrent.*; public class ThreadPoolDemo { public static void main(String[] args) throws InterruptedException { ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2); // 提交任务到 FixedThreadPool for (int i = 0; i < 5; i++) { int taskId = i; fixedThreadPool.submit(() -> { System.out.println("Task " + taskId + " is running on thread " + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }); } fixedThreadPool.shutdown(); // 关闭线程池 } } ``` 此代码展示了三种不同类型线程池的创建方法及任务提交流程。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值