0%

java | 单线程线程池

newSingleThreadExecutor

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

使用场景

  • 希望多个任务排队执行,线程固定为 1,任务多于 1 时,会放入无界队列排队,执行完毕后,这唯一线程也不会被释放

区别

  • 自己创建一个单线程串行执行任务,如果任务执行失败而终止那么,没有任何补救措施,而线程池还会创建一个新的线程,保证池的正常工作
  • Executors.newSingleThreadExecutor() 线程个数始终为 1,不能修改
    • FinalizableDelegatedExecutorService 应用的是装饰器模式,只能对外暴露 ExecutorService 接口,因此不能调用 ThreadPoolExecutor 中特有方法
  • Executors.newFixedThreadPool(1) 初始为 1,以后还可以修改
    • 对外暴露的是 ThreadPoolExecutor 对象,可以强转后调用 setCorePoolSize 等方法进行修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.redisc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j(topic = "c.Test")
public class Run {

public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.execute(() -> {
log.debug("1");
int i = 1 / 0;
});

pool.execute(() -> {
log.debug("2");
});

pool.execute(() -> {
log.debug("3");
});

}
}

输出

1
2
3
4
5
6
7
8
23:49:58.157 [pool-1-thread-1] DEBUG c.Test - 1
23:49:58.160 [pool-1-thread-2] DEBUG c.Test - 2
23:49:58.160 [pool-1-thread-2] DEBUG c.Test - 3
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
at com.redisc.Run.lambda$main$0(Run.java:16)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
请我喝杯咖啡吧~