0%

java | 带缓冲的线程池

newCachedThreadPool

1
2
3
4
5
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}

特点

  • 核心线程数是 0,最大线程数是 Integer.MAX_VALUE,救急线程的生存时间是 60s
    • 全部都是救急线程
    • 救急线程可以无限创建
  • 队列采用 SynchronousQueue
    • 没有线程来取是放不进去的
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.redisc;

import lombok.extern.slf4j.Slf4j;

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

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

public static void main(String[] args) throws InterruptedException {
SynchronousQueue<Integer> integers = new SynchronousQueue<>();
new Thread(() -> {
try {
log.debug("putting {}", 1);
integers.put(1);
log.debug("{} putted", 1);

log.debug("putting {}", 2);
integers.put(2);
log.debug("{} putted", 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t1").start();

Thread.sleep(1000);

new Thread(() -> {
try {
log.debug("taking {}", 1);
integers.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t2").start();

new Thread(() -> {
try {
log.debug("taking {}", 2);
integers.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t3").start();

}
}

输出

1
2
3
4
5
6
23:36:29.807 [t1] DEBUG c.Test - putting 1
23:36:30.806 [t2] DEBUG c.Test - taking 1
23:36:30.806 [t1] DEBUG c.Test - 1 putted
23:36:30.806 [t1] DEBUG c.Test - putting 2
23:36:30.806 [t3] DEBUG c.Test - taking 2
23:36:30.806 [t1] DEBUG c.Test - 2 putted
  • 整个线程池表现为随着任务量不断增长,没有上限,当任务执行完毕,空闲 1 分钟后释放线程
  • 适合任务比较密集,但每个人物执行时间比较短的情况
请我喝杯咖啡吧~