chenlianxiang_Blog 2019-03-28 18:32 采纳率: 66.7%
浏览 1908
已采纳

springboot 多线程 获取不到 service 空对象 无法执行更新数据库

 @Bean
    public ExecutorService executorService(){
        ExecutorService executorService=Executors.newFixedThreadPool(7);
        return executorService;
    }


          @RequestMapping(value = "threadPool")
    public void threadPool() throws Exception {
        int size=6;

        List<stockBean> stockBeans = stockService.queryStock();
        List<stockBean> retInfoList2 = new ArrayList<stockBean>();
//        ExecutorService executorService=Executors.newFixedThreadPool(10);
        List<List<stockBean>> subTaskList = new ArrayList<List<stockBean>>();

        List<FutureTask<List<stockBean>>> futureList=new ArrayList<>();

        //切分任务
        for (int i =0 ;i<=stockBeans.size();i=i+size) {

            subTaskList.add(stockBeans.subList(i, Math.min(i+size, stockBeans.size())));
        }
        for (List<stockBean> alist : subTaskList) {

            FutureTask<List<stockBean>> task = new FutureTask<List<stockBean>>(new theadPool1(alist));
            executorService.execute(task);
            futureList.add(task);

        }

        for (FutureTask<List<stockBean>> futureTask : futureList) {

            retInfoList2.addAll(futureTask.get());
        }

    }



        @Component
public class theadPool1 implements Callable<List<stockBean>> {

    @Autowired
    private IStockService stockService;



    private List<stockBean> stockBeans=null;
    public theadPool1(List<stockBean> stockBeans){
        this.stockBeans=stockBeans;
    }
    @Override
    public List<stockBean> call() throws Exception {
        System.out.println("当前运行的线程名称:" + Thread.currentThread().getName());
        stockService.uptStock(stockBeans);
        System.out.println("当前运行的线程ID:" + Thread.currentThread().getId());
        return stockBeans;

无法进入  stockService.uptStock(stockBeans); 方法进行更新

求大佬帮助
  • 写回答

1条回答 默认 最新

  • 红橡树 2019-03-28 19:07
    关注

    你的theadPool1 是@Component组件形式,也就是说这个实例是由spring容器进行维护的,它里面的对象也都是依赖spring进行实例化,但在你的public void threadPool() throws Exception {}这个方法里,你是通过new theadPool1(alist)的形式去实例化这个对象的,这样其中的private IStockService stockService;对象是空值,正常情况下如果你执行调用就会报空指针异常。解决办法由public void threadPool() throws Exception {}这个方法所在的类去实例化类threadPool,也就是通过@Autowired去实例化

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大