项目中大家基本都使用过线程池,节省线程创建和销毁的成本。Java JDK提供了几种线程池,那么如何选择合适的线程池?这就需要对每一种线程池有较详细的了解,然后根据实际业务类型,选择对应的线程池。 本文主要介绍FixedThreadPool。
定义
/**
* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue. At any point, at most
* {@code nThreads} threads will be active processing tasks.
* If additional tasks are submitted when all threads are active,
* they will wait in the queue until a thread is available.
* If any thread terminates due to a failure during execution
* prior to shutdown, a new one will take its place if needed to
* execute subsequent tasks. The threads in the pool will exist
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
*
* @param nThreads the number of threads in the pool
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
简要说明,FixedThreadPool,也就是可重用固定线程数的线程池。 它corePoolSize和 maximumPoolSize是一样的。并且他的keepAliveTime=0, 也就是当线程池中的线程数大于corePoolSize, 多余的空闲线程会被***立即***终止。
它的基本执行过程如下
1, 如果当前运行的线程数少于corePoolSize, 会立刻创建新线程执行任务。
2,当线程数到达corePoolSize后,将任务加入到LinkedBlockingQueue中。
3,当线程执行完任务后,会循环从LinkedBlockingQueue中获取任务来执行。
FixedThreadPool使用了LinkedBlockingQueue, 也就是无界队列(队列最大可容纳Integer.MAX_VALUE), 因此会造成以下影响:
a, 线程池线程数到达corePoolSize后,任务会被存放在LinkedBlockingQueue中
b, 因为无界队列,运行中(未调用shutdown()或者shutdownNow()方法)的不会拒绝任务(队列无界,可以放入"无限"任务)
实际代码
提交到线程池的任务
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
@Slf4j
@Getter
class MyTask implements Runnable {
private String name;
public MyTask(String name) {
this.name = name;
}
@Override
public void run() {
try {
long threadId = Thread.currentThread().getId();
Long duration = (long) (Math.random() * 10);
log.info("Doing a task during : {}, threadId={}" , name , threadId);
TimeUnit.SECONDS.sleep(duration);
log.info("done a task during : {}, threadId={}" , name , threadId);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
提交过程
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Slf4j
public class FixedThreadPoolExecutorDemo2 {
public static void main(String[] args) {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
MyTask task = new MyTask("Task " + i);
if (i == 2) {
try {
//这里刻意等待task0和task1完成。
TimeUnit.SECONDS.sleep(70);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//线程数
int activeCount = executor.getActiveCount();
long taskCount = executor.getTaskCount();
BlockingQueue queue = executor.getQueue();
log.info("A new task has been added {}, activeCount={}, taskCount={}, queue={}",
task.getName(), activeCount, taskCount, queue.size());
executor.execute(task);
}
System.out.println("Maximum threads inside pool " + executor.getMaximumPoolSize());
executor.shutdown();
}
}
分析
重点看日志,从日志我们可以看出它的运行过程与前面的分析一致。
11:47:28.963 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 0, activeCount=0, taskCount=0, queue=0
11:47:28.972 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 1, activeCount=1, taskCount=1, queue=0
11:47:28.973 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - Doing a task during : Task 0, threadId=9
11:47:28.976 [pool-1-thread-2] INFO com.yq.threadpool.MyTask - Doing a task during : Task 1, threadId=10
11:47:31.976 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - done a task during : Task 0, threadId=9
11:47:36.976 [pool-1-thread-2] INFO com.yq.threadpool.MyTask - done a task during : Task 1, threadId=10
11:48:38.972 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 2, activeCount=0, taskCount=2, queue=0
11:48:38.973 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 3, activeCount=1, taskCount=3, queue=0
11:48:38.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - Doing a task during : Task 2, threadId=11 (task2 和task3提交时,虽然thread 9和10已经完成了task0和task1,但是线程池为task2生成了thread 11,这是因为线程池设定的线程数是4,现在还没有到达4个线程,所以新提交的任务,就为该任务创建一个线程)
11:48:38.974 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 4, activeCount=2, taskCount=4, queue=0
11:48:38.974 [pool-1-thread-4] INFO com.yq.threadpool.MyTask - Doing a task during : Task 3, threadId=12 (task2 和task3提交时,虽然thread 9和10已经完成了task0和task1,但是线程池位task3生成了thread 12,这是因为线程池设定的线程数是4,现在还没有到达4个线程(现在有3个),所以新提交的任务,就为该任务创建一个线程)
11:48:38.974 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 5, activeCount=2, taskCount=5, queue=1
11:48:38.974 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - Doing a task during : Task 4, threadId=9 (线程总数应达到4个了,新的任务需要等待,然后循环使用以前的线程,这里使用thread 9)
11:48:38.975 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - done a task during : Task 4, threadId=9
11:48:38.975 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 6, activeCount=3, taskCount=6, queue=1
11:48:38.975 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 7, activeCount=3, taskCount=7, queue=1
11:48:38.975 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 8, activeCount=3, taskCount=8, queue=2
11:48:38.975 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 9, activeCount=3, taskCount=9, queue=3
Maximum threads inside pool 4
11:48:38.975 [pool-1-thread-2] INFO com.yq.threadpool.MyTask - Doing a task during : Task 5, threadId=10
11:48:38.976 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - Doing a task during : Task 6, threadId=9
11:48:41.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - done a task during : Task 2, threadId=11
11:48:41.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - Doing a task during : Task 7, threadId=11
11:48:41.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - done a task during : Task 7, threadId=11
11:48:41.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - Doing a task during : Task 8, threadId=11
11:48:43.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - done a task during : Task 8, threadId=11
11:48:43.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - Doing a task during : Task 9, threadId=11
11:48:43.976 [pool-1-thread-2] INFO com.yq.threadpool.MyTask - done a task during : Task 5, threadId=10
11:48:45.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - done a task during : Task 9, threadId=11
11:48:45.976 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - done a task during : Task 6, threadId=9
11:48:46.974 [pool-1-thread-4] INFO com.yq.threadpool.MyTask - done a task during : Task 3, threadId=12
Process finished with exit code 0