java数据库连接池的优化动态代理多线程线程通讯

1.数据可连接配置文件 jdbc配置文件
driver:oracle.jdbc.driver.OracleDriver
path:jdbc:oracle:thin:@127.0.0.1:1521:ORCL
countSize:3
user:scott
password:tiger


2.线程类
package com.cgm.util;

import java.sql.Connection;
import java.sql.Statement;

public class MyThread extends Thread{

@Override
public void run() {
Connection conn=null;
try {
conn=Conutils.getCon(); //取得链接
System.err.println(this.getName()+","+conn);
conn.setAutoCommit(false);//设置失去的开始
String sql=" insert into userss values('"+this.getName()+"','Tom','49')";
Statement st=conn.createStatement();
st.execute(sql);
conn.commit();
System.out.println(this.getName()+"子线程执行完成");
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
conn.setAutoCommit(true);
conn.close(); //close变成了还链接
} catch (Exception e2) {
e2.printStackTrace();
}

}




}

}


3代理类
package com.cgm.threadpool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

public class ConUtils1 {

private static List pool=new ArrayList();
static{
try {

Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@127.0.0.1:1521:ORCL";
String user="scott";
String passWord="tiger";
for (int i = 0; i < 3; i++) {
final Connection conn= DriverManager.getConnection(url, user, passWord);
//产生被代理对象对conn进行代理
Object connObj=Proxy.newProxyInstance(
ConUtils1.class.getClassLoader(),
new Class[]{Connection.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {

//method.getName()拦截目标类别的所有方法
if (method.getName().equals("close")) {
System.out.println("不能关啊,还要链接");
}else{
System.out.println(method.getName());
return method.invoke(conn, args);
}


synchronized (pool) {
//这个peoxy就是 connObj
pool.add((Connection) proxy);
//加进去了就放行
pool.notify();
}

return null;
}
});


pool.add((Connection) connObj); //加被代理对象能拦截啊,只能拦截代理对象
}
} catch (Exception e) {
throw new RuntimeException();
}
}

/*
* 提供一个静态工厂方法 返回一个链接
*/
public static Connection getCon(){
synchronized (pool) {

if (pool.size()==0) { //发现没有----等待
try {
//Thread.sleep(1000);
pool.wait(); //没有就等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getCon(); //递归 直到拿到为止
}


Connection conn=pool.remove(0); //返回一个代理的Connection类
return conn;
}
}
}



4.测试类

package com.cgm.util;

public class ThreadDemo {
public static void main(String[] args) throws Exception {
for (int i = 0; i < 30; i++) {
new MyThread().start();
}

}
}

你可能感兴趣的:(java基础)