@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); 方法進行更新
求大佬幫助
2 回答

慕斯王
TA貢獻1864條經(jīng)驗 獲得超2個贊
你的theadPool1 是@Component組件形式,也就是說這個實例是由spring容器進行維護的,它里面的對象也都是依賴spring進行實例化,但在你的public void threadPool() throws Exception {}這個方法里,你是通過new theadPool1(alist)的形式去實例化這個對象的,這樣其中的private IStockService stockService;對象是空值,正常情況下如果你執(zhí)行調(diào)用就會報空指針異常。解決辦法由public void threadPool() throws Exception {}這個方法所在的類去實例化類threadPool,也就是通過@Autowired去實例化

富國滬深
TA貢獻1790條經(jīng)驗 獲得超9個贊
這邊 我后續(xù) 采用了兩種解決方法, 一種 就是直接從 springboot 的上下文中 去獲取實例, 二就是直接將這個service 對象 直接通過傳參的方式進行傳遞,
添加回答
舉報
0/150
提交
取消