定长线程池 FixedThreadPool

博客介绍了使用定长线程池 FixedThreadPool 加速耗时操作的方法。包括定长线程池的声明,如声明由10个线程组成的池子;编写线程可实现 Runnable 或 Callable 接口;还提及了调用方式,以及主线程等待子线程结束再继续执行的判断代码。

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

有些时候,我们会使用线程池去加速某些耗时操作,常常使用到定长线程池 FixedThreadPool。主线程如何等待子线程结束,再继续执行。

1. 定长线程池声明。声明10个线程组成的池子

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);

2.编写自己的线程 thread。可以实现 Runnable接口,参数自己定义,可以将需要返回的值以参数的形式传递进来。

import java.util.List;
import java.util.Map;

public class FixedExcutorThread implements Runnable {

//...

  @Override
  public void run() {
    // do something
  }
}

也可以实现Callable接口,定义好需要返回的类型

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;

public class SingleExcutorThread implements Callable<Map<Integer, TbBean>> {
  private  WarehouseMapper mapper;

  SingleExcutorThread(WarehouseMapper mapper){
    this.mapper = mapper;
  }

  @Override
  public Map<Integer, TbBean> call(){
    List<TbBean> storageTbBeanList = mapper.selectWarehousesFromStorageTb();
    return storageTbBeanList.stream()
        .collect(Collectors.toMap(TbBean::getId, a -> a, (k1, k2) -> k1));
  }
}

3. 调用方式

// Runnable 
  
FixedExcutorThread thread = new FixedExcutorThread(...); // 自行修改参数
fixedThreadPool.execute(thread);

// Callable
SingleExcutorThread calledThread = new SingleExcutorThread(...);
Future<Map<Integer, DmStorageTbBean>> future = fixedThreadPool.execute(calledThread);
xxx = future.get(); // get获取call()返回结果。它是阻塞方法

fixedThreadPool.shutdown(); // 关闭,子线程不结束线程池不会关闭

4.如果主线程需等待子线程结束再做其他事。由下面代码进行判断

fixedThreadPool.awaitTermination(60, TimeUnit.MINUTES); // 等待子线程最长时间 1 个小时
if (fixedThreadPool.isTerminated()) {
   //...
}

参考文献
https://blog.youkuaiyun.com/u011974987/article/details/51027795
https://www.jianshu.com/p/7afa3c663863

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值