java 线程池详解
Executor框架是一种将线程的创建和执行分离的机制。它基于Executor和ExecutorService接口,及这两个接口的实现类ThreadPoolExecutor展开,Executor有一个内部线程池,并提供了将任务传递到池中线程以获得执行的方法,可传递的任务有如下两种:通过Runnable接口实现的任务和通过Callable接口实现的任务。在这两种情况下,只需要传递任务到执行器,执行器即可使用线程池中的线程或新创建的线程来执行任务。执行器也决定了任务执行时间。
java提供了四种线程池的实现: (这4中线程池底层都是使用ThreadPoolExecutor类实现的
)
(1)newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
(2)newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
(3)newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
(4)newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
下面就对这些线程池的使用方式进行简要的代码介绍:
首先是可缓存线程池:
1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3.
4. public class ThreadPoolDemo {
5. public static void main (String[] args) {
6. ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
7. for(int i = 0; i < 10; i++) {
8. final int index = i;
9. try {
10. Thread.sleep(index*1000);
11. } catch (InterruptedException e) {
12. e.printStackTrace();
13. }
14. cachedThreadPool.execute(new Runnable () {
15. public void run () {
16. System.out.println(index);
17. }
18. });
19. }
20. }
21.
22. }
然后是定长线程池:
1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3.
4. public class ThreadPoolDemo {
5. public static void main (String[] args) {
6. ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
7. for(int i = 0; i < 10; i++) {
8. final int index = i;
9. fixedThreadPool.execute(new Runnable () {
10. public void run () {
11. System.out.println(index);
12. try {
13. Thread.sleep(2000);
14. } catch (InterruptedException e) {
15. // TODO Auto-generated catch block
16. e.printStackTrace();
17. }
18. }
19. });
20. }
21. }
22. }
然后是定长线程池支持定时和周期性任务:
1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3. import java.util.concurrent.ScheduledExecutorService;
4. import java.util.concurrent.TimeUnit;
5.
6. public class ThreadPoolDemo {
7. public static void main (String[] args) {
8. ScheduledExecutorService scheduleThreadPool = Executors.newScheduledThreadPool(5);
9. scheduleThreadPool.schedule(new Runnable() {
10. public void run() {
11. System.out.println("delay 3 seconds");
12. }
13. }, 3, TimeUnit.SECONDS);
14. }
15. }
最后是:单线程化线程池
1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3. import java.util.concurrent.ScheduledExecutorService;
4. import java.util.concurrent.TimeUnit;
5.
6. public class ThreadPoolDemo {
7. public static void main (String[] args) {
8. ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
9. for(int i = 0; i < 10; i++) {
10. final int index = i;
11. singleThreadExecutor.execute(new Runnable() {
12. public void run() {
13. try {
14. System.out.println(index);
15. Thread.sleep(2000);
16. } catch (InterruptedException e) {
17. e.printStackTrace();
18. }
19. }
20. });
21. }
22. }
23. }
好了四种线程池的使用上面已经介绍完了,现在来看看线程池的原理吧,其中最重要的就是ThreadPoolExecutor类的构造函数,你会有疑惑,上面程序压根没有出现这个ThreadPoolExecutor类啊,其实,如果你追代码到
Executors.newSingleThreadExecutor()
中查看你会发现如下代码:
1. public static ExecutorService newSingleThreadExecutor() {
2. return new FinalizableDelegatedExecutorService
3. (new ThreadPoolExecutor(1, 1,
4. 0L, TimeUnit.MILLISECONDS,
5. new LinkedBlockingQueue<Runnable>()));
6. }
这四类线程池类底层都是ThreadPoolExecutor类进行初始化的,你不信你可以一个一个点进去看一下,而且我告诉你,四大线程池是通过使用ThreadPoolExecutor构造函数实现的;你看看下面实现就知道了
1. public static ExecutorService newCachedThreadPool() {
2. return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
3. 60L, TimeUnit.SECONDS,
4. new SynchronousQueue<Runnable>());
5. }
1. public static ExecutorService newFixedThreadPool(int nThreads) {
2. return new ThreadPoolExecutor(nThreads, nThreads,
3. 0L, TimeUnit.MILLISECONDS,
4. new LinkedBlockingQueue<Runnable>());
5. }
1. public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
2. return new ScheduledThreadPoolExecutor(corePoolSize);//这边居然不是直接调ThreadPoolExecutor构造函数,但是我们追一下代码看看下面这个函数你就会明白
3.
4. }
1. public ScheduledThreadPoolExecutor(int corePoolSize) {
2. super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
3. new DelayedWorkQueue());//里面使用了父类的构造函数,下面就是本类和父类的继承关系,看看他的父类是什么,你就明白了
4. }
1. public class ScheduledThreadPoolExecutor
2. extends ThreadPoolExecutor
3. implements ScheduledExecutorService
OK。到这里,你就应该知道我们今天的主角是谁了---------ThreadPoolExecutor
好了我们可以来看看这个类的构造函数源码了:
1. public ThreadPoolExecutor(int corePoolSize,
2. int maximumPoolSize,
3. long keepAliveTime,
4. TimeUnit unit,
5. BlockingQueue<Runnable> workQueue) {
6. this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
7. Executors.defaultThreadFactory(), defaultHandler);
8. }
9. 看见有好多参数啊,现在主要对其中的构造参数进行解释:
10.
11. corePoolSize:核心池大小,意思是当超过这个范围的时候,就需要将新的线程放到等待队列中了即workQueue;
12.
13. maximumPoolSize:线程池最大线程数量,表明线程池能创建的最大线程数
14.
15. keepAlivertime:当活跃线程数大于核心线程数,空闲的多余线程最大存活时间。
16.
17. unit:存活时间的单位
18.
19. workQueue:存放任务的队列---阻塞队列
20.
21. handler:超出线程范围(maximumPoolSize)和队列容量的任务的处理程序
22.
23.
24. 我们执行线程时都会调用到ThreadPoolExecutor的execute()方法,现在我们来看看这个方法的源码(就是下面这段代码了,这里面有一些注释解析),我直接来解释一下吧:在这段代码中我们至少要看懂一个逻辑:当当前线程数小于核心池线程数时,只需要添加一个线程并且启动它,如果线程数数目大于核心线程池数目,我们将任务放到workQueue中,如果连workQueue满了,那么就要拒绝任务了。详细的函数我就不介绍了
25.
26.
27. public void execute(Runnable command) {
28. if (command == null)
29. throw new NullPointerException();
30. /*
31. * Proceed in 3 steps:
32. *
33. * 1. If fewer than corePoolSize threads are running, try to
34. * start a new thread with the given command as its first
35. * task. The call to addWorker atomically checks runState and
36. * workerCount, and so prevents false alarms that would add
37. * threads when it shouldn't, by returning false.
38. *
39. * 2. If a task can be successfully queued, then we still need
40. * to double-check whether we should have added a thread
41. * (because existing ones died since last checking) or that
42. * the pool shut down since entry into this method. So we
43. * recheck state and if necessary roll back the enqueuing if
44. * stopped, or start a new thread if there are none.
45. *
46. * 3. If we cannot queue task, then we try to add a new
47. * thread. If it fails, we know we are shut down or saturated
48. * and so reject the task.
49. */
50. int c = ctl.get();
51. if (workerCountOf(c) < corePoolSize) {
52. if (addWorker(command, true))
53. return;
54. c = ctl.get();
55. }
56. if (isRunning(c) && workQueue.offer(command)) {
57. int recheck = ctl.get();
58. if (! isRunning(recheck) && remove(command))
59. reject(command);
60. else if (workerCountOf(recheck) == 0)
61. addWorker(null, false);
62. }
63. else if (!addWorker(command, false))
64. reject(command);
65. }