JDK1.5中引入了强大的concurrent包,其中ThreadPoolExecutor是运用场景最多的并发框架,几乎所有需要异步或并发执行任务的程序都可以使用线程池。在开发过程中合理地使用线程池能够带来 3 个好处。
- 降低资源消耗:通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
- 提高响应速度:当任务到达时,任务可以不需要等到线程创建就能立即执行。
- 提高线程的可管理性:线程是稀缺资源,如果无限制地创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一分配、调优和监控。
线程池给我们带来了极大的方便,但是,要做到合理利用线程池,必须对其实现原理了如指掌,对于线程池使用不当,其效率可能达不到预期的效果。
线程池的实现原理
线程池的主要处理流程
线程池 execute() 方法
ThreadPoolExecutor 执行 execute() 方法分下面四种情况:
- 如果当前运行的线程少于corePoolSize,则创建新线程来执行任务(注意,执行这一步骤需要获取全局锁)。
- 如果运行的线程等于或多于corePoolSize,则将任务加入 BlockingQueue。
- 如果无法将任务加入 BlockingQueue(队列已满),则创建新的线程来处理任务(注意这一步骤需要获取全局锁)。
- 如果创建新线程将使当前运行的线程超出 maxmumPoolSize,任务将被拒绝,并调用
RejectedExecutionHandler.rejectedExecution() 方法。
ThreadPoolExecutor 采取上述步骤的总体设计思路,是为了在执行 execute() 方法时,尽可能得避免获取全局锁(那将会是一个严重的可伸缩瓶颈)。在ThreadPoolExecutor 完成预热之后(当前运行的线程数大于等于 corePoolSize),几乎所有的execute() 方法调用都是指向步骤 2,而步骤 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54/** * Executes the given task sometime in the future. The task * may execute in a new thread or in an existing pooled thread. * * If the task cannot be submitted for execution, either because this * executor has been shutdown or because its capacity has been reached, * the task is handled by the current {@code RejectedExecutionHandler}. * * @param command the task to execute * @throws RejectedExecutionException at discretion of * {@code RejectedExecutionHandler}, if the task * cannot be accepted for execution * @throws NullPointerException if {@code command} is null */ public void execute(Runnable command) { if (command == null) throw new NullPointerException(); /* * Proceed in 3 steps: * * 1. If fewer than corePoolSize threads are running, try to * start a new thread with the given command as its first * task. The call to addWorker atomically checks runState and * workerCount, and so prevents false alarms that would add * threads when it shouldn't, by returning false. * * 2. If a task can be successfully queued, then we still need * to double-check whether we should have added a thread * (because existing ones died since last checking) or that * the pool shut down since entry into this method. So we * recheck state and if necessary roll back the enqueuing if * stopped, or start a new thread if there are none. * * 3. If we cannot queue task, then we try to add a new * thread. If it fails, we know we are shut down or saturated * and so reject the task. */ int c = ctl.get(); if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); } if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); if (! isRunning(recheck) && remove(command)) reject(command); else if (workerCountOf(recheck) == 0) addWorker(null, false); } else if (!addWorker(command, false)) reject(command); }
工作线程
线程创建时,会将线程封装成工作线程 Worker,Worker 在执行完任务后,还会循环获取工作队列里的任务来执行。我们可以从 Worker 类的 run() 方法里看到这点。
线程池中的线程执行任务分两种情况
- 在 execute() 方法中创建一个线程时,会让这个线程执行当前任务。
- 这个线程执行完上图 1 中的任务后,会反复从 BlockingQueue 获取任务来执行。
线程池的使用
线程池的创建
我们可以通过 TreadPoolExecutor 来创建一个线程池
1
2
3
4
5
6
7
8
9
10public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler); }
参考资料:
《Java 并发编程的艺术》
https://blog.csdn.net/huakaihualuo012/article/details/79752117
最后
以上就是有魅力茉莉最近收集整理的关于并发编程-Java中的线程池的全部内容,更多相关并发编程-Java中内容请搜索靠谱客的其他文章。
发表评论 取消回复