手机版
你好,游客 登录 注册
背景:
阅读新闻

Java并发包中的几种ExecutorService

[日期:2012-01-15] 来源:Linux社区  作者:wawlian [字体:大 中 小]

1.CachedThreadPool

CachedThreadPool首先会按照需要创建足够多的线程来执行任务(Task)。随着程序执行的过程,有的线程执行完了任务,可以被重新循环使用时,才不再创建新的线程来执行任务。我们采用《Thinking In Java》中的例子来分析。

首先,任务定义如下(实现了Runnable接口,并且复写了run方法):

  1. package net.jerryblog.concurrent; 
  2. public class LiftOff implements Runnable{ 
  3.     protected int countDown = 10; //Default 
  4.     private static int taskCount = 0; 
  5.     private final int id = taskCount++;  
  6.     public LiftOff() {} 
  7.     public LiftOff(int countDown) { 
  8.         this.countDown = countDown; 
  9.     } 
  10.     public String status() { 
  11.         return "#" + id + "(" + 
  12.             (countDown > 0 ? countDown : "LiftOff!") + ") "; 
  13.     } 
  14.     @Override 
  15.     public void run() { 
  16.         while(countDown-- > 0) { 
  17.             System.out.print(status()); 
  18.             Thread.yield(); 
  19.         } 
  20.          
  21.     }    
  22. } 

采用CachedThreadPool方式执行编写的客户端程序如下:

  1. package net.jerryblog.concurrent; 
  2. import java.util.concurrent.ExecutorService; 
  3. import java.util.concurrent.Executors; 
  4. public class CachedThreadPool { 
  5.     public static void main(String[] args) { 
  6.         ExecutorService exec = Executors.newCachedThreadPool(); 
  7.         for(int i = 0; i < 10; i++) { 
  8.             exec.execute(new LiftOff()); 
  9.         } 
  10.         exec.shutdown();     
  11.     } 
  12. } 

上面的程序中,有10个任务,采用CachedThreadPool模式,exec没遇到一个LiftOff的对象(Task),就会创建一个线程来处理任务。现在假设遇到到第4个任务时,之前用于处理第一个任务的线程已经执行完成任务了,那么不会创建新的线程来处理任务,而是使用之前处理第一个任务的线程来处理这第4个任务。接着如果遇到第5个任务时,前面那些任务都还没有执行完,那么就会又新创建线程来执行第5个任务。否则,使用之前执行完任务的线程来处理新的任务。

linux
相关资讯       Java教程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款