自定义线程池代码实现--1

//连接池
public class Pool {
//定义线程池的大小
private final int poolSize;
//连接对象数组
private Connection[] connections;
//连接池中连接对象状态  0:可用  1:不可用
private AtomicIntegerArray states;

//初始化连接池对象
public Pool(int poolSize) {
    this.poolSize = poolSize;
    for (int i = 0; i < poolSize; i++) {
        connections[i] = new MyConnection();
    }
    states = new AtomicIntegerArray(new int[poolSize]);
}

//获取连接
public Connection getConnection(){
    while (true){
        //遍历查找未被使用的连接
        for (int i = 0; i < poolSize; i++) {
            //CAS保证并发下的线程安全 (乐观锁)
            if (states.compareAndSet(i,0,1)) {
                return connections[i];
            }
        }
        //没有连接 让线程等待
        synchronized (this){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//释放连接
public void releaseConnection(Connection conn){
    //遍历判断是否是连接池中的对象
    for (int i = 0; i < poolSize; i++) {
        if (connections[i]==conn){
            states.set(i,0);
            //有连接释放  唤醒线程池中所有等待的线程
            synchronized (this){
                this.notifyAll();
            }
            break;
        }
    }

}
}

猜你喜欢

转载自blog.csdn.net/weixin_44017425/article/details/107563097
今日推荐