java信号量实现对象池

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));
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37732829/article/details/111909094