---
title: "并发编程---------初解线程池"
author: "xiaowei2002"
date: "2015-08-06T11:56:42Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2015-08-06T11:56:42Z"
id: 2233235
url: "https://xiaowei2002.iteye.com/blog/2233235"
---

并发编程系列文章:  
      初解线程池:[http://ray-yui.iteye.com/blog/2072463](http://ray-yui.iteye.com/blog/2072463)  
      详解线程池:[http://ray-yui.iteye.com/blog/2075311](http://ray-yui.iteye.com/blog/2075311)  
      并发数据类型:[http://ray-yui.iteye.com/blog/2080454](http://ray-yui.iteye.com/blog/2080454)  
      并发数据结构:[http://ray-yui.iteye.com/blog/2084202](http://ray-yui.iteye.com/blog/2084202)  
      volatile:[http://ray-yui.iteye.com/blog/2231474](http://ray-yui.iteye.com/blog/2231474)  
      判断线程安全:[http://ray-yui.iteye.com/blog/2232931](http://ray-yui.iteye.com/blog/2232931)

**什么是线程池:**  
      线程池和对象池链接池一样保存着多个线程对象**,为了节省系统在多线程并发时不断创建线程和销毁线程所带来的额外开销.线程池的基本功能就是线程的复用**

**JDK5线程池:**  
      为了能够更好的控制多线程,JDK5后提供了Executor框架,它是一个现成的线程池实现,帮助开发人员有效的进行线程控制

**Executor框架使用:**

Java代码 [![复制代码](http://ray-yui.iteye.com/images/icon_copy.gif)](http://ray-yui.iteye.com/blog/2072463 "复制代码") [![收藏代码](http://ray-yui.iteye.com/images/icon_star.png)![](http://ray-yui.iteye.com/images/spinner.gif)]()

01. public class TestMain {
02. @Test
03. public void testExecutor() {
04. Executor threadPool = null;
05. /*
06. * 该方法返回一个固定线程数量的线程池,该线程池中的线程数量 是固定不变的,
07. * 当一个新任务被提交时,若然没有空闲线程,则会暂时存储在一个任务队列中,
08. * 待有空闲的线程便处理任务队列中的任务
09. \*/
10. threadPool = Executors.newFixedThreadPool(10);
11. /*
12. * 该方法返回一个只有一个线程的线程池,当一个新任务被提交后,
13. * 会进入任务队列待有空闲线程时即处理任务队列中的任务
14. \*/
15. threadPool = Executors.newSingleThreadExecutor();
16. /*
17. * 该方法返回一个可根据实际任务数量调整线程数量的线程池,
18. * 该线程池的线程数量是不固定的,若有空闲线程,则会优先处理任务,
19. * 若所有线程都在执行任务时又有新的任务被提交,则会创建新的线程去处理任务
20. \*/
21. threadPool = Executors.newCachedThreadPool();
22. /*
23. * 每个创建线程池的方法都有ThreadFactory的重载
24. \*/
25. threadPool = Executors.newFixedThreadPool(10, new ThreadFactory() {
26. @Override
27. public Thread newThread(Runnable r) {
28. /*
29. * 使用ThreadFactory能控制线程产生时的细节操作
30. \*/
31. Thread thread = new Thread(r);
32. // 设置为守护线程
33. thread.setDaemon(true);
34. // 线程优先级为最高
35. thread.setPriority(Thread.MAX\_PRIORITY);
36. return thread;
37. }
38. });
39. // 提交一個任务
40. threadPool.execute(new Runnable() {
41. @Override
42. public void run() {
43. // executor logic
44. }
45. });
46. /*
47. *  但我们一般使用ExecutorService方便我們操作线程池,
48. *  通过ExecutorService我们能使用更多的方式操作线程池
49. \*/
50. /*
51. *  其实通过Executors创建的线程池返回的都是ExecutorService对象,
52. *  Executor是ExecutorService的父类
53. \*/
54. ExecutorService service = (ExecutorService) threadPool;
55. /*
56. * 提交一个有返回值(计算结果)的任务 温馨提示,若然任务需要返回计算结果,
57. * 使用service.submit(),若然任务不需要
58. * 任何返回结果,使用service.execute();
59. \*/
60. Future&lt;Integer&gt; future = service.submit(new Callable&lt;Integer&gt;() {
61. @Override
62. public Integer call() throws Exception {
63. return 10;
64. }
65. });
66. /*
67. * 当线程池使用完毕可以使用shutdown关闭线程池,
68. * shutdown是较为温柔的关闭方式,等待任务执行完毕后才关闭线程池
69. * 若然想马上关闭,可以使用service.shutdownNow();
70. \*/
71. service.shutdown();
72. //更多的API请参考JDK帮助文档
73. }
74. }

```
public class TestMain {

    @Test
    public void testExecutor() {
        
        Executor threadPool = null;

        /*
         * 该方法返回一个固定线程数量的线程池,该线程池中的线程数量 是固定不变的,
         * 当一个新任务被提交时,若然没有空闲线程,则会暂时存储在一个任务队列中,
         * 待有空闲的线程便处理任务队列中的任务
         */
        threadPool = Executors.newFixedThreadPool(10);

        /*
         * 该方法返回一个只有一个线程的线程池,当一个新任务被提交后,
         * 会进入任务队列待有空闲线程时即处理任务队列中的任务
         */
        threadPool = Executors.newSingleThreadExecutor();

        /*
         * 该方法返回一个可根据实际任务数量调整线程数量的线程池,
         * 该线程池的线程数量是不固定的,若有空闲线程,则会优先处理任务,
         * 若所有线程都在执行任务时又有新的任务被提交,则会创建新的线程去处理任务
         */
        threadPool = Executors.newCachedThreadPool();

        /*
         * 每个创建线程池的方法都有ThreadFactory的重载
         */
        threadPool = Executors.newFixedThreadPool(10, new ThreadFactory() {

            @Override
            public Thread newThread(Runnable r) {
                /*
                 * 使用ThreadFactory能控制线程产生时的细节操作
                 */
                Thread thread = new Thread(r);
                // 设置为守护线程
                thread.setDaemon(true);
                // 线程优先级为最高
                thread.setPriority(Thread.MAX_PRIORITY);
                return thread;
            }
        });

        // 提交一個任务
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                // executor logic
            }
        });

        /*
         *  但我们一般使用ExecutorService方便我們操作线程池,
         *  通过ExecutorService我们能使用更多的方式操作线程池
         */

        
        /*
         *  其实通过Executors创建的线程池返回的都是ExecutorService对象,
         *  Executor是ExecutorService的父类
         */
        ExecutorService service = (ExecutorService) threadPool;

        
        /*
         * 提交一个有返回值(计算结果)的任务 温馨提示,若然任务需要返回计算结果,
         * 使用service.submit(),若然任务不需要
         * 任何返回结果,使用service.execute();
         */
        Future<Integer> future = service.submit(new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                return 10;
            }
        });

        /*
         * 当线程池使用完毕可以使用shutdown关闭线程池, 
         * shutdown是较为温柔的关闭方式,等待任务执行完毕后才关闭线程池
         * 若然想马上关闭,可以使用service.shutdownNow();
         */
        service.shutdown();
        
        //更多的API请参考JDK帮助文档
    }
}
```

      JDK5后提供了Executor框架方便了开发人员,提供了线程池的实现和简便的API操控线程池,推荐读者在使用多线程时优先使用JDK内置线程池