问题场景:
需要在线程池中的线程执行完后将数据全部返回,但是现在是返回了部分的数据,未将线程池中的线程的执行结果全部返回
JSONObject res = new JSONObject(); //返回前台的数据
long start = System.currentTimeMillis();
log.info("======接入系統上報量線程執行開始=======");
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( // 定义线程池
3,
5,
2L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
try{
statisticSystemNum.stream().forEach(t -> {
threadPoolExecutor.execute(() ->{
t.put("value", tj07Mapper.countOneByOne(0,druidType,gc0100));// 查询数据库,并将数据设置到res中
log.info("執行了tttt====>" + t.get("value"));
});
});
}catch (Exception e){
e.printStackTrace();
}finally {
threadPoolExecutor.shutdown();
long end = System.currentTimeMillis();
log.info("======接入系統上報量線程執行結束=====共花費=="+(end-start)+"ms");
}
res.put("statisticSystemNum",statisticSystemNum);
return res;
}
使用ThreadGroup实现主线程等待所有子线程完成。
public class ThreadGroupDemo {
public static void main(String[] args) {
System.out.println("main start");
ThreadGroup tg = new ThreadGroup("Parent ThreadGroup");
for (int j = 0; j < 10; j++) {
new Thread(tg, "t" + j) {
public void run() {
System.out.println("Thread: " + getName() + " running");
int small = 0;
int large = 10;
try {
Thread.sleep(1000 * (int) (Math.random() * (large - small + 1) + small));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
while (tg.activeCount() > 0) {
try {
System.out.println("Waiting for " + tg.activeCount() + " CThreads to Complete");
Thread.sleep(1000); // Main Thread or someThradObject.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("main end");
}
}