1 public class JdbcUtil2 { 2 //声明连接池<放到LinkedList中,操作其中对象的速度快 只需要改变连接> 3 private static LinkedList<Connection> connectionspool=new LinkedList<Connection>(); 4 //静态代码块 5 static{ 6 try { 7 String url="jdbc:mysql://localhost:3306/jdbcdb"; 8 String user="root"; 9 String password="mysql"; 10 Class.forName("com.mysql.jdbc.Driver"); 11 //创建3个连接并将它们代理 12 for(int i=0;i<3;i++) 13 { 14 final Connection conn=DriverManager.getConnection(url, user, password); 15 //对conn进行代理 16 Object proxyobj= Proxy.newProxyInstance( 17 JdbcUtil2.class.getClassLoader(), 18 new Class[]{Connection.class}, 19 new InvocationHandler() { 20 public Object invoke(Object proxy, Method method, Object[] args) 21 throws Throwable { 22 //是否是close方法 23 if(method.getName().equals("close")) 24 { 25 synchronized(connectionspool){ 26 connectionspool.addLast((Connection)proxy); 27 connectionspool.notify(); 28 } 29 return null;//如果调用的是close()方法,不会调用代理类的方法,会调用代理 30 } 31 return method.invoke(conn, args); 32 } 33 }); 34 35 connectionspool.add((Connection)proxyobj); 36 37 } 38 } catch (SQLException e) { 39 // TODO Auto-generated catch block 40 e.printStackTrace(); 41 } catch (ClassNotFoundException e) { 42 // TODO Auto-generated catch block 43 e.printStackTrace(); 44 } 45 } 46 47 48 public static Connection getConnection() 49 { 50 synchronized(connectionspool) 51 { 52 if(connectionspool.size()==0) 53 { 54 try { 55 connectionspool.wait(); 56 } catch (InterruptedException e) { 57 // TODO Auto-generated catch block 58 e.printStackTrace(); 59 } 60 return getConnection(); 61 } 62 else { 63 Connection conn=connectionspool.removeFirst(); 64 System.err.println("pool中还有连接数:"+connectionspool.size()); 65 return conn; 66 } 67 } 68 } 69 }
利用多线程测试代理连接池
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 public class TestProxy { 2 public static void main(String[] args) { 3 for(int i=0;i<3000;i++) 4 { 5 new MyThread().start(); 6 } 7 } 8 } 9 10 class MyThread extends Thread 11 { 12 @Override 13 public void run() { 14 Connection con = null; 15 try{ 16 con = JdbcUtil2.getConnection(); 17 System.err.println(this.getName()+","+con); 18 con.setAutoCommit(false);//设置事务的开始 19 String sql = "insert into users values('"+this.getName()+"','Tom','44')"; 20 Statement st = con.createStatement(); 21 st.execute(sql); 22 con.commit(); 23 System.err.println(this.getName()+"子线程执行完成。。。。。"); 24 }catch(Exception e){ 25 e.printStackTrace(); 26 }finally{ 27 try { 28 con.setAutoCommit(true); 29 con.close(); 30 } catch (SQLException e) { 31 e.printStackTrace(); 32 } 33 } 34 } 35 }