package Thread;
import java.util.*;
import java.util.concurrent.*;
public class Callable_线程池 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// TODO Auto-generated method stub
// List<FutureTask<Integer>> futureTasks=new ArrayList<>();
ExecutorService executorService = Executors.newFixedThreadPool(10);
// long start=System.currentTimeMillis();
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
Integer res = new Random().nextInt(100);
return res;
}
};
// 异步提交
//第一种办法用futureTask包装返回值
//https://blog.csdn.net/mack415858775/article/details/51507660
for (int i = 0; i < 10; i++) {
FutureTask<Integer> futureTask = new FutureTask<>(callable);
// futureTasks.add(futureTask);
executorService.submit(futureTask);
int res=(int) futureTask.get();
System.out.print(res+" ");
}
System.out.println("");
//另一种方法(线程池返回future来获取返回值)
//https://blog.csdn.net/qq_25806863/article/details/71214033
for(int i=0;i<10;i++){
Future future=executorService.submit(callable);
System.out.print(future.get()+" ");
}
// 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();
}
}