实际上嵌套任务没什么稀奇,原理与上一篇差不多,,可先看这个https://www.cnblogs.com/kexb/p/10228422.html package com.hra.riskprice; import com.hra.riskprice.SysEnum.Factor_Type; import com.hra.riskprice.pojo.RskFactor; import com.hra.riskprice.service.impl.RskFactorBulkMapper; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.*; import java.util.concurrent.*; @SpringBootApplication public class RiskpriceApplication { public static void main(String[] args) throws InterruptedException, ExecutionException{ new RiskpriceApplication().exec(); } void exec() throws InterruptedException, ExecutionException { //进行异步任务列表 List<FutureTask<Integer>> futureTasks = new ArrayList<FutureTask<Integer>>(); //线程池 初始化十个线程 和JDBC连接池是一个意思 实现重用 ExecutorService executorService = Executors.newFixedThreadPool(10); long start = System.currentTimeMillis(); int jj=0; //类似与run方法的实现 Callable是一个接口,在call中手写逻辑代码 for(int i=0;i<10;i++){ cccc c1=new cccc(); c1.setIndex(i); c1.setTaskName("外层任务"+i); FutureTask<Integer> futureTask = new FutureTask<Integer>(c1); futureTasks.add(futureTask); //提交异步任务到线程池,让线程池管理任务 特爽把。 //由于是异步并行任务,所以这里并不会阻塞 executorService.submit(futureTask); } int count = 0; for (FutureTask<Integer> futureTask : futureTasks) { //futureTask.get() 得到我们想要的结果 //该方法有一个重载get(long timeout, TimeUnit unit) 第一个参数为最大等待时间,第二个为时间的单位 //count+= futureTask.get(); } long end = System.currentTimeMillis(); System.out.println("线程池的任务全部完成:结果为:"+count+",main线程关闭,进行线程的清理"); System.out.println("使用时间:"+(end-start)+"ms"); //清理线程池 executorService.shutdown(); } private int arg; class cccc implements Callable<Integer>{ private String taskName; private int index; public int getIndex(){ return index; } public void setIndex(int i){ this.index=i; } @Override public Integer call() throws Exception { Integer res = new Random().nextInt(100); Thread.sleep(1000); System.out.println("任务执行:获取到结果 :" +taskName+"是"+res); ExecutorService executorService = Executors.newFixedThreadPool(10); List<FutureTask<Integer>> futureTasks = new ArrayList<FutureTask<Integer>>(); for(int i=0;i<10;i++){ Callable<Integer> c1 = new Callable<Integer>(){ @Override public Integer call() throws Exception { //System.out.println("任务执行 is "+jj1+"个"); Integer res = new Random().nextInt(100); Thread.sleep(1000); System.out.println(taskName+ "---内部任务执行:获取到结果 :"+res); return res; } }; FutureTask<Integer> futureTask = new FutureTask<Integer>(c1); futureTasks.add(futureTask); //提交异步任务到线程池,让线程池管理任务 特爽把。 //由于是异步并行任务,所以这里并不会阻塞 executorService.submit(futureTask); } return res; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } } }