话不多说,亲测成功代码如下:
package day16;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.LinkedList;
/**
* 简易版连接池
*/
public class ConnectionPool {
//静态Connection队列
private static LinkedList<Connection> connections;
//加载驱动
static{
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
/**
* 获取连接,多线程访问并发控制
*/
public synchronized static Connection getConnection(){
try{
if(connections ==null){
connections =new LinkedList<Connection>();
for(int i =0;i<10;i++){
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/spark-1",
"root",
"root"
);
connections.push(conn);
}
}
}catch(Exception e){
e.printStackTrace();
}
return connections.poll();
}
public static void returnConnection(Connection conn){
connections.push(conn);
}
}