多线程笔记(二)线程池 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

转载于:https://www.cnblogs.com/ainsliaea/p/11372982.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值