日常随笔之线程池invokeAll使用风险

话不多说直接上代码,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();
}
}

posted @ 2020-10-31 10:46  于林富  阅读(2319)  评论(0编辑  收藏  举报