jdbc数据库连接池1

数据库连接池

解决:资源浪费,无法创建指定数目的连接,耗时

自定义连接池

使用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();
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值