0%

java | 固定大小的线程池

newFixedThreadPool。

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

特点

  • 核心线程数 == 最大线程数「没有救急线程」
  • 阻塞队列是无界的,可以放任意数量的任务

适用于任务量已知,相对耗时的任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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) {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.execute(() -> {
log.debug("1");
});
pool.execute(() -> {
log.debug("2");
});
pool.execute(() -> {
log.debug("3");
});
}
}

输出

1
2
3
23:15:59.050 [pool-1-thread-1] DEBUG c.Test - 1
23:15:59.050 [pool-1-thread-2] DEBUG c.Test - 2
23:15:59.057 [pool-1-thread-1] DEBUG c.Test - 3
请我喝杯咖啡吧~