java 数据连接池的最基本的实现

1.连接池类
package com.cgm.threadpool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

public class ConUtils {

public static  Connection conn;

private static List<Connection> pool=new ArrayList<Connection>();
static{
   try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@127.0.0.1:1521:ORCL";
for (int i = 0; i < 3; i++) {
   //创建三个链接
conn= DriverManager.getConnection(url,"scott","tiger");
pool.add(conn);  //三个链接放入连接池
}
System.out.println("链接是"+pool);
} catch (Exception e) {
      throw new RuntimeException(e.getMessage(),e);
}
 
}

public static  Connection getConnection(){
synchronized (pool) {
conn= pool.remove(0);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("====还有多少个=="+pool.size());
return conn;
}
}

//还回链接
public  static void  back(Connection con){
System.err.println("还连接:"+con);
pool.add(con);
}


}

//2子线程
package com.cgm.threadpool;

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

public class MyThread extends  Thread{

@Override
public void run() {
Connection conn=null;

try {
conn=ConUtils.getConnection();  //取得链接
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();

  //
//new MyThread().start();
//Thread.sleep(100);

System.out.println(this.getName()+"子线程执行完成");
// Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}finally{

try {
conn.setAutoCommit(true);
//conn.close(); 不能管 关闭的链接是不能用了
ConUtils.back(conn);  //还连接
} catch (Exception e2) {
e2.printStackTrace();
}

}


}
   
}





//主线程测试
package com.cgm.threadpool;

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

public class ThreadDemo  {
public static void main(String[] args) throws Exception {

/**
Connection conn=ConUtils.getConnection();  //取得链接
conn.setAutoCommit(false);//设置失去的开始
String sql=" insert into userss values('AA','libao','44')";
Statement st=conn.createStatement();
st.execute(sql);
new MyThread().start();
Thread.sleep(100);
conn.commit();
System.out.println("主线程执行完成");
*/
for (int i = 0; i < 14; i++) {
new MyThread().start();
}

}
}








你可能感兴趣的:(java)