1 //实现DataSource接口 2 public class MyConn implements DataSource { 3 //声明池管理对象 4 private LinkedList<Connection> pool =new LinkedList<Connection>(); 5 //在构造函数中初始化,创建多个连接 6 public MyConn() 7 { 8 try { 9 Class.forName("com.mysql.jdbc.Driver"); 10 String url="jdbc:mysql://localhost:3306/jdbcdb"; 11 for(int i=0;i<3;i++) 12 { 13 final Connection conn =DriverManager.getConnection(url,"root","mysql"); 14 15 Object ProxyedConn= Proxy.newProxyInstance( 16 MyConn.class.getClassLoader(), //类加载器 17 new Class[]{Connection.class}, //被代理类的父接口 18 new InvocationHandler() { //句柄,获取代理类的方法 19 public Object invoke(Object proxyedConnection, Method method, Object[] args) 20 throws Throwable { 21 22 if(method.getName().equals("close")) 23 { 24 synchronized (pool) { 25 pool.addLast((Connection)proxyedConnection); 26 pool.notify(); 27 } 28 return null; 29 } 30 //目标方法的返回值 31 Object returnValue=method.invoke(conn, args);//conn,你要代理的对象 32 return returnValue; 33 } 34 }); 35 36 pool.add((Connection)ProxyedConn); 37 } 38 } catch (Exception e) { 39 e.printStackTrace(); 40 } 41 } 42 43 public Connection getConnection() throws SQLException { 44 45 synchronized (pool) { 46 if(pool.size()==0)//池中是否还有连接,如果没有等待 47 { 48 try { 49 pool.wait(); 50 } catch (InterruptedException e) { 51 e.printStackTrace(); 52 } 53 return getConnection();//递归 54 } 55 56 Connection conn= pool.removeFirst();//移除第一个 57 return conn; 58 } 59 60 }