标签:executorService List 基础 Callable 线程 FutureTask new 多线程
四种开启线程方式:
一、Thread方式开启线程
二、Runable方式开发线程
三、Callable方式开启线程
①创建类实现Callable接口
/**
* @Author: ycw
* @Description: TODO
* @DateTime: 2021/7/7 14:03
**/
@Data
public class CustomerEcologyCallable implements Callable<List<CustomerEcology>> {
@Autowired
private CustomerEcologyMapper customerEcologyMapper;
private CustomerEcologyExample example;
private List<CustomerEcology> customerEcologyList;
//构造函数传实体类对象
public CustomerEcologyCallable(CustomerEcologyExample customerEcologyExample){
this.example=customerEcologyExample;
}
@Override
public List<CustomerEcology> call() throws Exception {
List<CustomerEcology> customerEcologyList = customerEcologyMapper.selectByExample(example);
return customerEcologyList;
}
}
②业务层创建线程执行futrue任务
//创建Callable对象任务
CustomerEcologyCallable customerEcologyCallable = new CustomerEcologyCallable(example);
//创建taskList集合
List<FutureTask<List<CustomerEcology>>> tasksList = new ArrayList<>();
//创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(50);
// 传入Callable对象建立FutureTask对象
FutureTask<List<CustomerEcology>> futureTask = new FutureTask<>(customerEcologyCallable);
提交给线程池执行任务,也能够经过 executorService.invokeAll(taskList)一次性提交全部任务;
tasksList.add(futureTask);
executorService.submit(futureTask);
//
List<CustomerEcology> asynResult = new LinkedList<>();
for (FutureTask<List<CustomerEcology>> futureTask1 : tasksList) {
if (asynResult.size()>0) {
try {
asynResult.add((CustomerEcology) futureTask1.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
//关闭线程池
executorService.shutdown();
标签:executorService,List,基础,Callable,线程,FutureTask,new,多线程 来源: https://blog.csdn.net/weixin_45476233/article/details/119385637
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。