多线程笔记(二)线程池 Executors

1. newSingleThreadExecutor 和 newFixedThreadPool(1) 的区别

    Fixed 直接返回一个 ThreadPoolExecutor,而 Single 在 ThreadPoolExecutor 的基础上封装了 FinalizableDelegatedExecutorService,源码:

1 public static ExecutorService newSingleThreadExecutor() {
2     return new FinalizableDelegatedExecutorService
3         (new ThreadPoolExecutor(1, 1,
4                                 0L, TimeUnit.MILLISECONDS,
5                                 new LinkedBlockingQueue<Runnable>()));
6 }

    在 FinalizableDelegatedExecutorService 类中重写了 Object 类的 finalize 方法,其中调用了 ExecutorService 的 shutdown 方法

1 static class FinalizableDelegatedExecutorService extends DelegatedExecutorService {
2     FinalizableDelegatedExecutorService(ExecutorService executor) {
3         super(executor);
4     }
5     protected void finalize() {
6         super.shutdown();
7     }
8 }

ThreadPoolExecutor 中提供了对线程池进行配置的方法(setXXX),而 Single 返回的是一个 FinalizableDelegatedExecutorService 其中并没有提供配置方法,它继承的顶层接口中也没有这些方法,所以无法进行配置,所以 Single 的方法注释是这样说的:

Unlike the otherwise equivalent {@code newFixedThreadPool(1)} the returned executor is guaranteed not to be reconfigurable to use additional threads.

区别:

    区别一:在垃圾回收的时候 Single 线程池相对 Fix 线程池多了一步关闭线程池,销毁线程的方法。
    区别二:Fix 单线程的时候后期可以配置/更改线程池,但是 Single 不可以。

2. 使用 invokeAll 执行多个 Callable,并将结果放在一个 List<Future> 中,可以方便的使用 Lambda 表达式进行处理

    demo:

 1 public static void main(String[] args) throws InterruptedException {
 2     ExecutorService executor = Executors.newWorkStealingPool();
 3 
 4     List<Callable<String>> callables = Arrays.asList(
 5             () -> "task1",
 6             () -> "task2",
 7             () -> "task3");
 8 
 9     executor.invokeAll(callables)
10             .stream()
11             .map(future -> {
12                 try {
13                     return future.get();
14                 } catch (Exception e) {
15                     throw new IllegalStateException(e);
16                 }
17             })
18             .forEach(System.out::println);
19 }

 

参考:

https://www.jianshu.com/p/a04de611c226

posted @ 2019-08-18 20:28  Ainsliaea  阅读(196)  评论(0编辑  收藏  举报