线程池谈谈我自己的理解吧:
- 先创建固定数量的连接,之后放在一个容器中
- 使用时从容器中拿
- 容器中的连接数量少于等于0,所有获取连接的动作等待;
- 容器中的连接数量大于0,则获取连接,在连接用完之后就返回到容器中
针对以上的理解,在编程中可以这样实现:
- 创建固定连接,放在 LinkedList<Connection> 中,选择这个是链表操作添加删除效率高
- 当 LinkedList.size() <= 0, 则该动作执行 wait() 操作
- 当 LinkedList.size() > 0, 获取连接 Connection con 交付获取者使用
- 当使用者使用完 con 后,调用 close() 时, 这时候将 con 添加到 LinkedList<Connection> 中,这个是编程难点
- 针对编程难点,我有2种解决方案
- 使用代理,在用户获取con时,我们返回的是代理后的con,这样,当客户使用con的close时,实际是执行LiskedList.add() 方法
- 规定使用者使用特定的close(Connection con) 方法;该方法简单,我就不实现了
下面是主要实现代码


1 public Connection getConnection() throws SQLException { 2 synchronized(MysqlUtils.class) { 3 while(list.size() <= 0 ) { 4 try { 5 log.info(Thread.currentThread().getName() + " wait() " ); 6 MysqlUtils.class.wait(); 7 } catch (InterruptedException e) { 8 log.error(" Thread " + Thread.currentThread().getName() 9 + " wait() error!"); 10 } 11 } 12 13 final Connection con = list.removeFirst(); 14 Connection conn = (Connection) Proxy.newProxyInstance(MysqlUtils.class.getClassLoader() 15 , new Class[]{Connection.class} 16 ,new InvocationHandler() { 17 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 18 if(!method.getName().equals("close")) { 19 return method.invoke(con, args); 20 } else { 21 synchronized(MysqlUtils.class) { 22 list.add(con); 23 MysqlUtils.class.notifyAll(); 24 log.info(Thread.currentThread().getName() + " release connection "); 25 return null; 26 } 27 } 28 } 29 }); 30 31 return conn; 32 33 } 34 }
池子的最大连接,最少连接,定时之类的很多都没有实现,只是简单的弄了一个固定连接数量
本篇博客参考了http://www.cnblogs.com/xdp-gacl/p/4002804.html 博客的代码,特此指出,也算是我自己的总结
以上有什么错误的地方,欢迎大家指出,目前也在学习中,一起进步哈