温馨提示×

java的threadpoolexecutor怎么使用

小亿
88
2023-07-06 15:21:33
栏目: 编程语言

ThreadPoolExecutor 是一个线程池的实现类,可以用来管理和执行多个线程任务。使用 ThreadPoolExecutor 需要以下几个步骤:

  1. 创建 ThreadPoolExecutor 对象:
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit, workQueue);
  • corePoolSize:核心线程数,线程池中始终保持的活动线程数。

  • maximumPoolSize:最大线程数,线程池中允许的最大线程数。

  • keepAliveTime:线程的空闲时间,当线程池中的线程数量超过核心线程数时,多余的空闲线程在等待任务时的最长存活时间。

  • TimeUnit:keepAliveTime 的时间单位。

  • workQueue:任务队列,用于保存等待执行的任务。

  1. 提交任务给线程池:
executor.execute(new Runnable() {
@Override
public void run() {
// 执行任务的代码
}
});

或者

Future<?> future = executor.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
// 执行任务的代码,并返回结果
return result;
}
});
  1. 关闭线程池:
executor.shutdown();

或者

executor.shutdownNow();
  • shutdown():平缓地关闭线程池,等待所有任务执行完毕后关闭。

  • shutdownNow():立即关闭线程池,不等待任务执行完毕。

以上是 ThreadPoolExecutor 的基本用法,还可以根据需要设置一些其他属性,如拒绝策略、线程工厂等。具体可以参考 ThreadPoolExecutor 的文档。

0