欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java信号量实现对象池

程序员文章站 2022-06-04 22:59:46
...
import java.util.List;
import java.util.Vector;
import java.util.concurrent.Semaphore;
import java.util.function.Function;

public class ObjectPool<T, R> {
    //对象池
    final List<T> pool;
    //用信号量实现限流器
    final Semaphore sem;

    public ObjectPool(int size, T t) {
        pool = new Vector<>();
        for(int i = 0; i < size; i++) {
            pool.add(t);
        }
        sem = new Semaphore(size);
    }

    //利用对象池的对象,调用func
    R exec(Function<T, R> func) {
        T t = null;
        R r = null;
        try {
            sem.acquire();
            t = pool.remove(0);
            r = func.apply(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            pool.add(t);
            sem.release();
        }
        return r;
    }

    public static void main(String[] args) {
        //创建对象池
        ObjectPool<String, String> pool = new ObjectPool<>(10, "demo");
        System.out.println(pool.exec(t-> System.currentTimeMillis() + t));
    }
}

 

相关标签: 信号量 对象池