多线程基础

四种开启线程方式:
一、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();
上一篇:主线程等待子线程,获取资源


下一篇:Java线程池中submit()和execute()方法有什么区别