单例模式的经典代码——线程池集合

来源:互联网 发布:产品介绍动画制作软件 编辑:程序博客网 时间:2024/04/30 08:08

import java.util.HashMap;

/**
 * 线程池集合类
 * 这个类负责在JVM中创建一个唯一的线程池集合,
 * 集合中有多个线程池,通过ThreadPoolSetCreator去创建
 * 这个类采用单例模式实现
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: AsiaInfo.com</p>
 *
 * @author Dapple Wang
 * @version 1.0
 */
public class ThreadPoolSet {

  private HashMap poolSet;
  private static ThreadPoolSet instance = null;

  /**
   * 构建器
   */
  private ThreadPoolSet() {
    poolSet = new HashMap();
  }

  /**
   * 取得线程池的集合的实例
   * @return ThreadPoolSet
   */
  public static synchronized ThreadPoolSet getInstance() {
    if (instance == null) {
      instance = new ThreadPoolSet();
    }
    return instance;
  }

  /**
   * 通过名字取得集合中线程池
   * @param poolName String 线程池的名字
   * @return ThreadPool
   */
  public ThreadPool getThreadPool(String poolName) {
    return (ThreadPool) poolSet.get(poolName);
  }

  /**
   * 添加线程池到集合
   * @param poolName String 线程池的名称
   * @param threadPool ThreadPool 线程池的实例
   */
  public void addThreadPool(String poolName, ThreadPool threadPool) {
    poolSet.put(poolName, threadPool);
  }

原创粉丝点击