为什么自定义连接池,加了锁还是不安全?

import java.sql.Connection;
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


求大神解答!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文子阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值