---
title: "Java线程池管理"
author: "gu6866"
date: "2012-09-07T11:52:44Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-09-07T11:52:44Z"
id: 1673420
url: "https://premier9527.iteye.com/blog/1673420"
---

import java.util.LinkedList;  
import java.util.Queue;  
import java.util.concurrent.ArrayBlockingQueue;  
import java.util.concurrent.Executors;  
import java.util.concurrent.RejectedExecutionHandler;  
import java.util.concurrent.ScheduledExecutorService;  
import java.util.concurrent.ScheduledFuture;  
import java.util.concurrent.ThreadPoolExecutor;  
import java.util.concurrent.TimeUnit;

public class ThreadPoolManager {

   
 /*  
  * 将构造方法访问修饰符设为私有，禁止任意实例化。  
  \*/  
 private ThreadPoolManager() {}  
   
 /*  
  \*实例化私有的静态成员变量线程池管理对象  
  \*/  
 private static ThreadPoolManager manager = new ThreadPoolManager();  
   
  /*  
   * 线程池单例创建方法  
   \*/  
 public static ThreadPoolManager newInstance() {  
   return manager;  
 }  
 

 // 线程池维护线程的最少数量  
 private final static int CORE\_POOL\_SIZE = 3;

 

 // 线程池维护线程的最大数量  
 private final static int MAX\_POOL\_SIZE = 10;

 

 // 线程池维护线程所允许的空闲时间  
 private final static int KEEP\_ALIVE\_TIME = 0;

 

 // 线程池所使用的缓冲队列大小  
 private final static int WORK\_QUEUE\_SIZE = 10;

 

 // 任务调度周期  
 private final static int TASK\_QOS\_PERIOD = 10;

 

 // 任务缓冲队列  
 private Queue&lt;Runnable&gt; taskQueue = new LinkedList&lt;Runnable&gt;();

 

  /*  
   * 线程池超出界线时将任务加入缓冲队列  
   \*/  
 final RejectedExecutionHandler handler = new RejectedExecutionHandler() {  
   public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {  
    taskQueue.offer(task);  
   }  
 };

 

  /*  
   * 将缓冲队列中的任务重新加载到线程池  
   \*/  
 final Runnable accessBufferThread = new Runnable() {  
   public void run() {  
    if (hasMoreAcquire()) {  
     threadPool.execute(taskQueue.poll());  
    }  
   }  
 };

 

  /*  
   * 创建一个调度线程池  
   \*/  
 final ScheduledExecutorService scheduler = Executors .newScheduledThreadPool(1);

 

  /*  
   * 通过调度线程周期性的执行缓冲队列中任务  
   \*/  
 final ScheduledFuture&lt;?&gt; taskHandler = scheduler.scheduleAtFixedRate(  
    accessBufferThread, 0, TASK\_QOS\_PERIOD, TimeUnit.MILLISECONDS);

 

  /*  
   * 线程池  
   \*/  
 final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(  
    CORE\_POOL\_SIZE, MAX\_POOL\_SIZE, KEEP\_ALIVE\_TIME, TimeUnit.SECONDS,  
    new ArrayBlockingQueue&lt;Runnable&gt;(WORK\_QUEUE\_SIZE), this.handler);

 

  /*  
   * 消息队列检查方法  
   \*/  
 private boolean hasMoreAcquire() {  
   return !taskQueue.isEmpty();  
 }

 

  /*  
   * 向线程池中添加任务方法  
   \*/  
 public void addExecuteTask(Runnable task) {  
   if (task != null) {  
    threadPool.execute(task);  
   }  
 }

   
   
}