ExecutorService线程池

ExecutorService 建立多线程的步骤:

1。定义线程类
class Handler implements Runnable{
}
2。建立ExecutorService线程池
ExecutorService executorService = Executors.newCachedThreadPool();

或者

int cpuNums = Runtime.getRuntime().availableProcessors();
                //获取当前系统的CPU 数目
ExecutorService executorService =Executors.newFixedThreadPool(cpuNums * POOL_SIZE);
                //ExecutorService通常根据系统资源情况灵活定义线程池大小
3。调用线程池操作
循环操作,成为daemon,把新实例放入Executor池中
      while(true){
        executorService.execute(new Handler(socket)); 
           // class Handler implements Runnable{
        或者
        executorService.execute(createTask(i));
            //private static Runnable createTask(final int taskID)
      }

execute(Runnable对象)方法
其实就是对Runnable对象调用start()方法
(当然还有一些其他后台动作,比如队列,优先级,IDLE timeout,active激活等)


几种不同的ExecutorService线程池对象
1.newCachedThreadPool() 
-缓存型池子,先查看池中有没有以前建立的线程,如果有,就reuse.如果没有,就建一个新的线程加入池中
-缓存型池子通常用于执行一些生存期很短的异步型任务
 因此在一些面向连接的daemon型SERVER中用得不多。
-能reuse的线程,必须是timeout IDLE内的池中线程,缺省timeout是60s,超过这个IDLE时长,线程实例将被终止及移出池。
  注意,放入CachedThreadPool的线程不必担心其结束,超过TIMEOUT不活动,其会自动被终止。
2. newFixedThreadPool
-newFixedThreadPool与cacheThreadPool差不多,也是能reuse就用,但不能随时建新的线程
-其独特之处:任意时间点,最多只能有固定数目的活动线程存在,此时如果有新的线程要建立,只能放在另外的队列中等待直到当前的线程中某个线程终止直接被移出池子
-和cacheThreadPool不同,FixedThreadPool没有IDLE机制(可能也有,但既然文档没提,肯定非常长,类似依赖上层的TCP或UDP IDLE机制之类的),所以FixedThreadPool多数针对一些很稳定很固定的正规并发线程,多用于服务器
-从方法的源代码看,cache池和fixed 池调用的是同一个底层池,只不过参数不同:
fixed池线程数固定,并且是0秒IDLE(无IDLE)
cache池线程数支持0-Integer.MAX_VALUE(显然完全没考虑主机的资源承受能力),60秒IDLE  
3.ScheduledThreadPool
-调度型线程池
-这个池子里的线程可以按schedule依次delay执行,或周期执行
4.SingleThreadExecutor
-单例线程,任意时间池中只能有一个线程
-用的是和cache池和fixed池相同的底层池,但线程数目是1-1,0秒IDLE(无IDLE)


上面四种线程池,都使用Executor的缺省线程工厂建立线程,也可单独定义自己的线程工厂
下面是缺省线程工厂代码:
    static class DefaultThreadFactory implements ThreadFactory {
        static final AtomicInteger poolNumber = new AtomicInteger(1);
        final ThreadGroup group;
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null)? s.getThreadGroup() :Thread.currentThread().getThreadGroup();
          
            namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,namePrefix + threadNumber.getAndIncrement(),0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
也可自己定义ThreadFactory,加入建立池的参数中
 public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {


Executor的execute()方法
execute() 方法将Runnable实例加入pool中,并进行一些pool size计算和优先级处理
execute() 方法本身在Executor接口中定义,有多个实现类都定义了不同的execute()方法
如ThreadPoolExecutor类(cache,fiexed,single三种池子都是调用它)的execute方法如下:

    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
            if (runState == RUNNING && workQueue.offer(command)) {
                if (runState != RUNNING || poolSize == 0)
                    ensureQueuedTaskHandled(command);
            }
            else if (!addIfUnderMaximumPoolSize(command))
                reject(command); // is shutdown or saturated
        }
    }

1.CachedThreadPool

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

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

 

Java代码  收藏代码
  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方式执行编写的客户端程序如下: 

 

Java代码  收藏代码
  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个任务。否则,使用之前执行完任务的线程来处理新的任务。

2.FixedThreadPool

     FixedThreadPool模式会使用一个优先固定数目的线程来处理若干数目的任务。规定数目的线程处理所有任务,一旦有线程处理完了任务就会被用来处理新的任务(如果有的话)。这种模式与上面的CachedThreadPool是不同的,CachedThreadPool模式下处理一定数量的任务的线程数目是不确定的。而FixedThreadPool模式下最多 的线程数目是一定的。

    采用FixedThreadPool模式编写客户端程序如下:

 

Java代码  收藏代码
  1. package net.jerryblog.concurrent;   
  2. import java.util.concurrent.ExecutorService;   
  3. import java.util.concurrent.Executors;   
  4. public class FixedThreadPool {   
  5.     public static void main(String[] args) {  
  6.         //三个线程来执行五个任务   
  7.         ExecutorService exec = Executors.newFixedThreadPool(3);      
  8.         for(int i = 0; i < 5; i++) {   
  9.             exec.execute(new LiftOff());   
  10.         }   
  11.         exec.shutdown();   
  12.     }   
  13. }   

3.SingleThreadExecutor模式

    SingleThreadExecutor模式只会创建一个线程。它和FixedThreadPool比较类似,不过线程数是一个。如果多个任务被提交给SingleThreadExecutor的话,那么这些任务会被保存在一个队列中,并且会按照任务提交的顺序,一个先执行完成再执行另外一个线程。

    SingleThreadExecutor模式可以保证只有一个任务会被执行。这种特点可以被用来处理共享资源的问题而不需要考虑同步的问题。

    SingleThreadExecutor模式编写的客户端程序如下: 

 

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

    这种模式下执行的结果如下:

Java代码  收藏代码
  1. #0(9) #0(8) #0(7) #0(6) #0(5) #0(4) #0(3) #0(2) #0(1) #0(LiftOff!)  
  2. #1(9) #1(8) #1(7) #1(6) #1(5) #1(4) #1(3) #1(2) #1(1) #1(LiftOff!)   

    第一个任务执行完了之后才开始执行第二个任务。


转自:http://blog.csdn.net/luohai859/article/details/22744697

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值