话不多说直接上代码,invokeAll的使用方式如下图
public class Main { public static void main(String[] args) throws InterruptedException, ExecutionException { List<Callable<Integer>> tasks = new ArrayList<>(); for( int i = 0; i < 10; i++) { tasks.add(()->{ Random random = new Random(); int second = random.nextInt(10); Thread.sleep(second * 1000) ; return second; }); } ExecutorService executorService = Executors.newFixedThreadPool(10); List<Future<Integer>> futures = executorService.invokeAll(tasks); for( int i = 0; i < futures.size(); i++) { System.out.println(futures.get(i).get()); } executorService.shutdown(); }}
invokeAll的作用是:等待所有的任务执行完成后统一返回。
这里与大家分享的是:如果executorService是公共线程池慎用,如果这时候有另外一个请求也不断地往线程池里不断地方任务,这时候这个请求是不是就一直不停的阻塞了。
推荐写法如下:
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException, ExecutionException {
List<Future<Integer>> tasks = new ArrayList<>();
ExecutorService executorService = Executors.newFixedThreadPool(10);
for( int i = 0; i < 10; i++) {
Future<Integer> f = executorService.submit(() -> {
Random random = new Random();
int second = random.nextInt(10);
Thread.sleep(second * 1000);
return second;
});
tasks.add(f);
}
for( int i = 0; i < tasks.size(); i++) {
System.out.println(tasks.get(i).get());
}
executorService.shutdown();
}
}
原文转载:http://www.shaoqun.com/a/485821.html
usps国际快递查询:https://www.ikjzd.com/w/513
雨果网:https://www.ikjzd.com/w/1307
五洲会海购:https://www.ikjzd.com/w/1068
话不多说直接上代码,invokeAll的使用方式如下图publicclassMain{publicstaticvoidmain(String[]args)throwsInterruptedException,ExecutionException{List<Callable<Integer>>tasks=newArrayList<>();for(inti=0;i&
斑马物联:https://www.ikjzd.com/w/1316
sonar:https://www.ikjzd.com/w/215
亚马逊大卖:没有玩不转的"站外Deals "!:https://www.ikjzd.com/home/113379
美国白宫地址_美国白宫开放时间及门票信息:http://tour.shaoqun.com/a/61760.html
香港哪些地方可以露营?:http://tour.shaoqun.com/a/7426.html