利用java編寫mysql連接池的方法
具體內容如下:
public class ConnecionPool {
private int size;
List
connections = new ArrayList<>(); public ConnecionPool(int size){
this.size=size;
init();
}
public void init(){
try {
Class.forName("com.mysql.jdbc.Driver");
while (size--!=0){
connections.add(DriverManager.getConnection(jdbc:mysql://127.0.0.1:3306/d數據庫名稱, 用戶名,密碼)// );
}
}catch (Exception e){
e.printStackTrace();
}
}
public Connection getConnection(){
try {//如果沒有連接了,線程就等待
while (connections.isEmpty()){
this.wait();
}
}catch (Exception e){
e.printStackTrace();
}
return connections.remove(0);
}
public void returnConntion(Connection connection){
connections.add(connection);
this.notifyAll();
}
}