数据库连接池
解决:资源浪费,无法创建指定数目的连接,耗时
自定义连接池
使用java集合
java调用
package csdn1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.LinkedList;
import org.junit.Test;
//数据库连接池
/*
数据库连接池会先创建好一定数量的连接
当线程需要时,就从连接池里借用,无需自己重新创建,使用完后归还给连接池
连接不会关闭,不断被需要的线程循环使用,进而节约了启动和关闭连接的时间
*/
public class jdbc6 {
/*
// 1.自定义测试---单元测试行不通
@Test
public void test1() {
DefinePool pool = new DefinePool(5);
for (int i = 0; i < 100; i++) {
new Th("th" + i, pool).start();
System.out.println("sjdkalfj");
}
}
*/
public static void main(String[] args) {
DefinePool pool = new DefinePool(5);
for (int i = 0; i < 100; i++) {
new Th("th" + i, pool).start();
}
}
}
class Th extends Thread {
private DefinePool pool;
public Th(String name, DefinePool pool) {
super(name);
this.pool = pool;
}
@Override
public void run() {
String sql = "select name,password from user;";
Connection cn = pool.getConnection();
System.out.println(this.getName() + ":\t 获取了一根连接,并开始工作");
try (PreparedStatement ps = cn.prepareStatement(sql);) {
Thread.sleep(1000);
ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
pool.returnConnection(cn);
}
}
//1.自定义数据库连接池
class DefinePool {
LinkedList<Connection> pool = new LinkedList<Connection>();
private int size;
public DefinePool() {
super();
}
public DefinePool(int size) {
super();
this.size = size;
init(size);
}
public void init(int size) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydbs2";
for (int i = 0; i < size; i++) {
Connection cn = DriverManager.getConnection(url, "root", "root");
pool.add(cn);
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public synchronized Connection getConnection() {
while (pool.isEmpty()) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Connection cn = pool.poll();
return cn;
}
public synchronized void returnConnection(Connection cn) {
pool.add(cn);
this.notifyAll();
}
}