[Java 并发编程] 22. 线程池

2020-09-04

1. 线程池

当我们需要限制一个应用程序中同一时间运行的线程数量,我们通常使用线程池来实现。

通过把任务传递给线程池,只要线程池中有空闲的线程就将空闲的线程分配任务并执行任务,而不是给每个任务都创建一个新的线程。任务被插入到阻塞队列中,当线程池存在空的线程时,阻塞队列中的任务就被分配到空闲的线程中执行。

自Java 5 开始,java.util.concurrent 包中提供了线程池,比如:java.util.concurrent.ExecutorService.

2. 自定义线程池

阻塞队列

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
class BlockingQueue<E extends Runnable> {

private LinkedList<E> queue = new LinkedList<>();
private int limit;

/**
* 构造方法注入队列上限
*
* @param limit 队列上限
*/
public BlockingQueue(int limit) {
this.limit = limit;
}

public synchronized void enqueue(E e) throws InterruptedException {
while (queue.size() == limit) {
wait();
}
queue.add(e);
notifyAll();
}

public synchronized E dequeue() throws InterruptedException {
while (queue.size() == 0) {
wait();
}
notifyAll();
return queue.removeFirst();
}

}

线程池

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
class ThreadPool<R extends Runnable, T extends BaseThread> {

private BlockingQueue<R> blockingQueue;
private List<T> threads = new ArrayList<>();
private boolean stop = false;

@SuppressWarnings("unchecked")
public ThreadPool(int blockingQueueLimit, int threadNumber, Supplier<T> supplier) {
if (threadNumber < 1) {
throw new IllegalArgumentException("Param 'threadNumber' cannot be less than 1.");
}

//初始化阻塞队列
blockingQueue = new BlockingQueue<>(blockingQueueLimit);

//初始化线程池中的线程
IntStream.rangeClosed(1, threadNumber).forEach(i -> {
T t = supplier.get();
t.setBlockingQueue(blockingQueue);
threads.add(t);
});

//启动线程
for (T t : threads) {
t.start();
}
}

public synchronized void execute(R r) throws InterruptedException {
if (stop) {
throw new IllegalStateException("ThreadPool is stopped.");
}
//将任务添加到阻塞队列中
this.blockingQueue.enqueue(r);
}

public synchronized void doStop() {
this.stop = true;
for (T thread : threads) {
thread.interrupt();
}
}

}

自定义线程 BaseThread 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class BaseThread<R extends Runnable> extends Thread {

private BlockingQueue<R> blockingQueue;

public void setBlockingQueue(BlockingQueue<R> blockingQueue) {
this.blockingQueue = blockingQueue;
}

@Override
public void run() {
while (!this.isInterrupted()) {
try {
blockingQueue.dequeue().run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

测试

1
2
ThreadPool<Runnable, BaseThread<Runnable>> threadPool = new ThreadPool<>(2, 1, BaseThread::new);
threadPool.execute(() -> System.out.println("测试线程池"));

我们只需要将任务添加到阻塞队列中,线程池中的线程会对阻塞队列循环做出队操作,并执行任务,我们还可以通过调用doStop()方法停止线程池。