import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import com.mysql.jdbc.Driver;
/**
* 自定义数据库连接池
* @author Shinelon
*
*/
public class Demo05 {
private static LinkedList<Connection> connPool=null;
//注册驱动
static{
try {
DriverManager.registerDriver(new Driver());
connPool = new LinkedList<Connection>();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//构造方法
public Demo05(){
for (int i = 0; i <10; i++) {
Connection conn;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/exam?user=root&password=321");
connPool.add(conn);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized Connection getConnection(){
//返回最后一个并移除
return connPool.removeLast();
}
public void closeConn(Connection conn){
//关闭时,存回连接
connPool.addFirst(conn);
}
}
多线程测试:
import java.sql.Connection;
public class Demo06 {
public static void main(String[] args) {
final Demo05 demo05 = new Demo05();
// 创建两个线程
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 4; i++) {
Connection conn = demo05.getConnection();
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(i+":"+Thread.currentThread().getName()+":"+conn.toString());
//demo05.closeConn(conn);
}
}
}).start();
}
}
}
结果:
0:Thread-1:com.mysql.jdbc.JDBC4Connection@933c07
0:Thread-0:com.mysql.jdbc.JDBC4Connection@933c07
1:Thread-0:com.mysql.jdbc.JDBC4Connection@49ff3f
1:Thread-1:com.mysql.jdbc.JDBC4Connection@14ac54
2:Thread-1:com.mysql.jdbc.JDBC4Connection@13de2bd
2:Thread-0:com.mysql.jdbc.JDBC4Connection@1f12373
3:Thread-0:com.mysql.jdbc.JDBC4Connection@4e94a4
3:Thread-1:com.mysql.jdbc.JDBC4Connection@100b3c2
求大神解答!