当前位置: 首页 > news >正文

自定义连接线程池

今天来实现一个小小的自定义连接线程池,主要是为了让我们对线程池有一个大致的了解

我们的连接对象如下

实现这个连接对象就可以了

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

相关文章:

  • 408第一季 - 数据结构 - 图
  • mybatis执行insert如何返回id
  • 星耀8上市品鉴暨北京中和吉晟吉利银河用户中心开业媒体见面会
  • 基于多维视角的大模型提升认知医疗过程层次激励编程分析
  • 关于IE浏览器被绑定安装,还卸载不掉
  • RabbitMQ work模型
  • 云原生监控体系建设:Prometheus+Grafana的企业级实践
  • 【11408学习记录】考研写作双核引擎:感谢信+建议信复合结构高分模板(附16年真题精讲)
  • LeetCode - 148. 排序链表
  • 自动驾驶科普(百度Apollo)学习笔记
  • vue.js not detected解决方法
  • LinuxSamba服务器配置篇
  • 三级流水线是什么?
  • 12-OPENCV ROCKX项目 人脸拍照
  • 抖音怎么下载没有水印的视频?
  • 【计算机网络】三报文握手建立TCP连接
  • 【iOS】JSONModel源码学习
  • 台湾TEMI协会竞赛——0、竞赛介绍及开发板介绍
  • 数据类型 -- 转义字符
  • AI架构师如何创建自己的知识库
  • 建设政府信息资源共享网站/百色seo外包
  • 做易拉宝的素材网站/windows优化大师免费
  • 网站建设嘉兴公司电话/青岛seo建站
  • 做网站最低级的软件/南昌seo排名
  • 徐州做汽车销售的公司网站/佛山seo教程
  • 嘉兴云推广网站/如何制作网页最简单的方法