自定义连接线程池
今天来实现一个小小的自定义连接线程池,主要是为了让我们对线程池有一个大致的了解
我们的连接对象如下
实现这个连接对象就可以了
class MockConnect implements Connection {@Overridepublic Statement createStatement() throws SQLException {return null;}
下面是我们的自定义线程池的实现
class Pool {/*** 连接池大小*/private final Integer poolSize;/*** 连接池连接数组*/private Connection[] connections;/*** 连接数组的状态 0 空闲 1繁忙*/private AtomicIntegerArray status;public Pool(Integer poolSize) {this.poolSize = poolSize;this.connections = new Connection[poolSize];this.status = new AtomicIntegerArray(new int[poolSize]);for (Integer i = 0; i < poolSize; i++) {connections[i] = new MockConnect();}}/*** @Description 获取 连接**/public Connection getConnection() {while (true) {for (Integer i = 0; i < poolSize; i++) {Connection connection = this.connections[i];//多个线程 使用cas 保证 线程安全if (status.compareAndSet(i, 0, 1)) {System.out.println("获得");return connection;}}//循环一圈发现线程都是 满的 就休眠synchronized (this) {try {this.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}}//醒来之后接着循环}}/*** @Description: 释放连接**/public void freeConnection (Connection connection) {for (Integer i = 0; i < poolSize; i++) {if(this.connections[i]==connection){status.set(i,0);System.out.println("释放了");//释放了 就唤醒等待的synchronized (this){this.notifyAll();}break;}}}
}
可以看到 我们用一个connection 连接数组来保证每一个连接对象,然后用一个status 的cas数组来控制每一个连接对应只能获取一次,然后添加等待唤醒放置资源的浪费
测试用例
public class MyPool {public static void main(String[] args) {Pool pool = new Pool(3);for (int i = 0; i < 5; i++) {new Thread(new Runnable() {@Overridepublic void run() {Connection connection = pool.getConnection();try {Thread.sleep(1500);} catch (InterruptedException e) {throw new RuntimeException(e);}pool.freeConnection(connection);}}).start();}}}