Java四种线程池的使用以及callable future整理

Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。

newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

(1) newCachedThreadPool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例代码如下:

  1. package test;  
  2. import java.util.concurrent.ExecutorService;  
  3. import java.util.concurrent.Executors;  
  4. public class ThreadPoolExecutorTest {  
  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. }

线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。
 
(2) newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:

Java代码   收藏代码
  1. package test;  
  2. import java.util.concurrent.ExecutorService;  
  3. import java.util.concurrent.Executors;  
  4. public class ThreadPoolExecutorTest {  
  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.      try {  
  12.       System.out.println(index);  
  13.       Thread.sleep(2000);  
  14.      } catch (InterruptedException e) {  
  15.       e.printStackTrace();  
  16.      }  
  17.     }  
  18.    });  
  19.   }  
  20.  }  
  21. }  
 
因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。
定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()

(3)  newScheduledThreadPool
创建一个定长线程池,支持定时及周期性任务执行。延迟执行示例代码如下:

Java代码   收藏代码
  1. package test;  
  2. import java.util.concurrent.Executors;  
  3. import java.util.concurrent.ScheduledExecutorService;  
  4. import java.util.concurrent.TimeUnit;  
  5. public class ThreadPoolExecutorTest {  
  6.  public static void main(String[] args) {  
  7.   ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  
  8.   scheduledThreadPool.schedule(new Runnable() {  
  9.    public void run() {  
  10.     System.out.println("delay 3 seconds");  
  11.    }  
  12.   }, 3, TimeUnit.SECONDS);  
  13.  }  
  14. }  

 
表示延迟3秒执行。

定期执行示例代码如下:

  1. package test;  
  2. import java.util.concurrent.Executors;  
  3. import java.util.concurrent.ScheduledExecutorService;  
  4. import java.util.concurrent.TimeUnit;  
  5. public class ThreadPoolExecutorTest {  
  6.  public static void main(String[] args) {  
  7.   ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  
  8.   scheduledThreadPool.scheduleAtFixedRate(new Runnable() {  
  9.    public void run() {  
  10.     System.out.println("delay 1 seconds, and excute every 3 seconds");  
  11.    }  
  12.   }, 13, TimeUnit.SECONDS);  
  13.  }  
  14. }  

 
表示延迟1秒后每3秒执行一次。

 

(4) newSingleThreadExecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下:

Java代码   收藏代码
  1. package test;  
  2. import java.util.concurrent.ExecutorService;  
  3. import java.util.concurrent.Executors;  
  4. public class ThreadPoolExecutorTest {  
  5.  public static void main(String[] args) {  
  6.   ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();  
  7.   for (int i = 0; i < 10; i++) {  
  8.    final int index = i;  
  9.    singleThreadExecutor.execute(new Runnable() {  
  10.     public void run() {  
  11.      try {  
  12.       System.out.println(index);  
  13.       Thread.sleep(2000);  
  14.      } catch (InterruptedException e) {  
  15.       e.printStackTrace();  
  16.      }  
  17.     }  
  18.    });  
  19.   }  
  20.  }  
  21. }  

 
结果依次输出,相当于顺序执行各个任务。

你可以使用JDK自带的监控工具来监控我们创建的线程数量,运行一个不终止的线程,创建指定量的线程,来观察:
工具目录:C:\Program Files\Java\jdk1.6.0_06\bin\jconsole.exe
运行程序做稍微修改:

Java代码   收藏代码
  1. package test;  
  2. import java.util.concurrent.ExecutorService;  
  3. import java.util.concurrent.Executors;  
  4. public class ThreadPoolExecutorTest {  
  5.  public static void main(String[] args) {  
  6.   ExecutorService singleThreadExecutor = Executors.newCachedThreadPool();  
  7.   for (int i = 0; i < 100; i++) {  
  8.    final int index = i;  
  9.    singleThreadExecutor.execute(new Runnable() {  
  10.     public void run() {  
  11.      try {  
  12.       while(true) {  
  13.        System.out.println(index);  
  14.        Thread.sleep(10 * 1000);  
  15.       }  
  16.      } catch (InterruptedException e) {  
  17.       e.printStackTrace();  
  18.      }  
  19.     }  
  20.    });  
  21.    try {  
  22.     Thread.sleep(500);  
  23.    } catch (InterruptedException e) {  
  24.     e.printStackTrace();  
  25.    }  
  26.   }  
  27.  }  
  28. }  

 
效果如下:

 

选择我们运行的程序:

监控运行状态

 

转载自:http://cuisuqiang.iteye.com/blog/2019372    

http://blog.csdn.net/hupitao/article/details/24453083

 Callable接口类似于Runnable,从名字就可以看出来了,但是Runnable不会返回结果,并且无法抛出返回结果的异常,而Callable功能更强大一些,被线程执行后,可以返回值,这个返回值可以被Future拿到,也就是说,Future可以拿到异步执行任务的返回值,下面来看一个简单的例子:

<code class="hljs cs has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> CallableAndFuture {
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span>(String[] args) {
        Callable<Integer> callable = <span class="hljs-keyword">new</span> Callable<Integer>() {
            <span class="hljs-keyword">public</span> Integer <span class="hljs-title">call</span>() throws Exception {
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Random().nextInt(<span class="hljs-number">100</span>);
            }
        };
        FutureTask<Integer> future = <span class="hljs-keyword">new</span> FutureTask<Integer>(callable);
        <span class="hljs-keyword">new</span> Thread(future).start();
        <span class="hljs-keyword">try</span> {
            Thread.sleep(<span class="hljs-number">5000</span>);<span class="hljs-comment">// 可能做一些事情</span>
            System.<span class="hljs-keyword">out</span>.println(future.<span class="hljs-keyword">get</span>());
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {
            e.printStackTrace();
        } <span class="hljs-keyword">catch</span> (ExecutionException e) {
            e.printStackTrace();
        }
    }
}</code><ul style="" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li></ul><ul style="" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li></ul>

       FutureTask实现了两个接口,Runnable和Future,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值,那么这个组合的使用有什么好处呢?假设有一个很耗时的返回值需要计算,并且这个返回值不是立刻需要的话,那么就可以使用这个组合,用另一个线程去计算返回值,而当前线程在使用这个返回值之前可以做其它的操作,等到需要这个返回值时,再通过Future得到,岂不美哉!这里有一个Future模式的介绍:http://openhome.cc/Gossip/DesignPattern/FuturePattern.htm
       下面来看另一种方式使用Callable和Future,通过ExecutorService的submit方法执行Callable,并返回Future,代码如下:

<code class="hljs cs has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> CallableAndFuture {
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span>(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<Integer> future = threadPool.submit(<span class="hljs-keyword">new</span> Callable<Integer>() {
            <span class="hljs-keyword">public</span> Integer <span class="hljs-title">call</span>() throws Exception {
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Random().nextInt(<span class="hljs-number">100</span>);
            }
        });
        <span class="hljs-keyword">try</span> {
            Thread.sleep(<span class="hljs-number">5000</span>);<span class="hljs-comment">// 可能做一些事情</span>
            System.<span class="hljs-keyword">out</span>.println(future.<span class="hljs-keyword">get</span>());
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {
            e.printStackTrace();
        } <span class="hljs-keyword">catch</span> (ExecutionException e) {
            e.printStackTrace();
        }
    }
}</code><ul style="" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li></ul><ul style="" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li></ul>

       代码是不是简化了很多,ExecutorService继承自Executor,它的目的是为我们管理Thread对象,从而简化并发编程,Executor使我们无需显示的去管理线程的生命周期,是JDK 5之后启动任务的首选方式。
       执行多个带返回值的任务,并取得多个返回值,代码如下:

<code class="hljs cs has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> CallableAndFuture {
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span>(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        CompletionService<Integer> cs = <span class="hljs-keyword">new</span> ExecutorCompletionService<Integer>(threadPool);
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i < <span class="hljs-number">5</span>; i++) {
            final <span class="hljs-keyword">int</span> taskID = i;
            cs.submit(<span class="hljs-keyword">new</span> Callable<Integer>() {
                <span class="hljs-keyword">public</span> Integer <span class="hljs-title">call</span>() throws Exception {
                    <span class="hljs-keyword">return</span> taskID;
                }
            });
        }
        <span class="hljs-comment">// 可能做一些事情</span>
        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i < <span class="hljs-number">5</span>; i++) {
            <span class="hljs-keyword">try</span> {
                System.<span class="hljs-keyword">out</span>.println(cs.take().<span class="hljs-keyword">get</span>());
            } <span class="hljs-keyword">catch</span> (InterruptedException e) {
                e.printStackTrace();
            } <span class="hljs-keyword">catch</span> (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
} </code><ul style="" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li></ul><ul style="" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li></ul>

       其实也可以不使用CompletionService,可以先创建一个装Future类型的集合,用Executor提交的任务返回值添加到集合中,最后遍历集合取出数据,代码略。更新于2016-02-05,评论中就这个说法引发了讨论,其实是我没有讲清楚,抱歉。这里再阐述一下:提交到CompletionService中的Future是按照完成的顺序排列的,这种做法中Future是按照添加的顺序排列的。所以这两种方式的区别就像评论中fishjam所描述的那样。

       本文来自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/7451464,转载请注明。

Java并发编程:Callable、Future和FutureTask详情介绍

http://www.cnblogs.com/dolphin0520/p/3949310.html

http://www.cnblogs.com/starcrm/p/5010863.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值