Java多线程,线程池ThreadPoolExecutor使用详解

ThreadPoolExecutor.class构造方法参数讲解

参数名 作用
corePoolSize 核心线程池大小
maximumPoolSize 最大线程池大小
keepAliveTime 线程池中超过corePoolSize数目的空闲线程最大存活时间;可以allowCoreThreadTimeOut(true)使得核心线程有效时间
TimeUnit keepAliveTime时间单位
workQueue 阻塞任务队列
threadFactory 新建线程工厂
RejectedExecutionHandler 当提交任务数超过maxmumPoolSize+workQueue之和时,任务会交给RejectedExecutionHandler来处理

1.当线程池小于corePoolSize时,新提交任务将创建一个新线程执行任务,即使此时线程池中存在空闲线程。
2.当线程池达到corePoolSize时,新提交任务将被放入workQueue中,等待线程池中任务调度执行
3.当workQueue已满,且maximumPoolSize>corePoolSize时,新提交任务会创建新线程执行任务
4.当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理
5.当线程池中超过corePoolSize线程,空闲时间达到keepAliveTime时,关闭空闲线程
6.当设置allowCoreThreadTimeOut(true)时,线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭

示例代码:

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class testThreadPool {

   /**
    * 线程计数 
    */
   private static int count = 0;
   public static void main(String[] args) {
      
      /**
       * 通常会使用一个队列,进行排序
       */
      BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(25);
      
      /**
       * 如果使用无界的队列,当出现攻击时,容易导致内存泄漏。
       */
      //LinkedBlockingDeque<Runnable> queue = new LinkedBlockingDeque<>();
      
      /**
       * 线程池
       */
      ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 10, 30, TimeUnit.MINUTES, queue);
      
      /**
       * 重写Handler抛出来的线程重新加进去
       */
      pool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
         
         @Override
         public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            // TODO Auto-generated method stub
            while (true) {
               if (queue.size() < 24) {
                  System.out.println("++++++++++++++Runnable");
                  executor.execute(r);
                  break;
               }
            }
         }
      });

      /**
       * 定义一个定时器,每2秒创建10个进程
       */
      Timer timer = new Timer();
      timer.schedule(new TimerTask() {
         
         @Override
         public void run() {
            // TODO Auto-generated method stub
            
            for(int i = 0;i<10;i++) {
               count++;
               doWork work = new doWork();
               pool.execute(work);
               
            }
            
            if (count >= 200) {
               timer.cancel();
            }
         }
      }, 0,2000);
      
      /**
       * 定时检查线程的状况
       */
      new Timer().schedule(new TimerTask() {
         @Override
         public void run() {
            // TODO Auto-generated method stub
            System.err.println(">>当前队列:"+queue.size());
            System.err.println(">>线程数:"+count);
            System.err.println(">>当前ActiveCount:"+pool.getActiveCount());
            System.err.println(">>当前TaskCount:"+pool.getTaskCount());
            System.err.println(">>当前PoolSize:"+pool.getPoolSize());
         }
      }, 1000,1000);
      
   }
}

class doWork implements Runnable{
   

   @Override
   public void run() {
      // TODO Auto-generated method stub
      
      try {
         /**
          * 模拟真实环境,睡眠3秒
          */
         Thread.sleep(3000);
         System.out.println("线程id:"+Thread.currentThread().getId()+" 线程名称:"+Thread.currentThread().getName());
      } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      
   }

}

 

API文档:

http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html

Leave a Comment

关于深蓝

仅仅是一个对编程很有爱好的人.
Copyright © 2008-2016 lanxinbase.com Rights Reserved. | 粤ICP备14086738号 |