信号量实现对象池

class ObjPool<T,R>{
  final List<T> pool;
  //信号量实现限流器
  final Semaphore sem;
  //构造方法
  ObjectPool(int size,T t){
    pool = new Vector<T>(){};
    for(int i=0; i<size; i++){
      pool.add(t);
    }
    sem = new Semaphore(size);
  }
  
  R exec(Function<T,R> func){
    T t = null;
    sem.acquire();
    try{
      t = pool.remove(0);
      return func.apply(t);
    }finally{
      pool.add(t);
      sem.release();
    }
  }

  //创建线程池
  ObjPool<Long,String> pool =
    new ObjPool<Long, String>(10,2);
  //通过对象池获取t,之后执行
  pool.exec(t -> {
    System.out.println(t);
    return t.toString();
  })
}





原文地址:https://www.cnblogs.com/zhangchiblog/p/10676942.html