连接错误,说我con关闭,但是我并没有
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"
并且,我的模拟购买好像失效了
全部代码
package Test;
import java.sql.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class IncrTest {
//声明Connection对象
static Connection con;
//驱动程序名
static String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
static String url = "jdbc:mysql://localhost:3306/test";
//MySQL配置时的用户名
static String user = "root";
//MySQL配置时的密码
static String password = "root";
public static void RunMethod(){
//遍历查询结果集
try {
//加载驱动程序
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url,user,password);
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
//要执行的SQL语句
String sql = "update goods set num = num -1 where id = 1 and num>0 for update ";
Integer num = statement.executeUpdate(sql);
} catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功获取!!");
}
}
public static void concurrenceTest (){
/**
* 模拟高并发情况代码
*/
final AtomicInteger atomicInteger = new AtomicInteger(0);
final CountDownLatch countDownLatch = new CountDownLatch(1000); // 相当于计数器,当所有都准备好了,再一起执行,模仿多并发,保证并发量
final CountDownLatch countDownLatch2 = new CountDownLatch(1000); // 保证所有线程执行完了再打印atomicInteger的值
ExecutorService executorService = Executors.newFixedThreadPool(10);
try {
for (int i = 0; i < 1000; i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
countDownLatch.await(); //一直阻塞当前线程,直到计时器的值为0,保证同时并发
} catch (InterruptedException e) {
e.printStackTrace();
}
//每个线程增加1000次,每次加1
for (int j = 0; j < 1000; j++) {
//atomicInteger.incrementAndGet();
//购买商品
RunMethod();
}
countDownLatch2.countDown();
}
});
countDownLatch.countDown();
}
countDownLatch2.await();// 保证所有线程执行完
System.out.println(atomicInteger);
executorService.shutdown();
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
concurrenceTest();
}
}
没说你CON关闭,说的是“Too many connections”。
嗯
Connection Statement 这些都没有关闭,肯定会资源泄露
下面的模拟购买没用是怎么回事?
表结构
goods
id name_tc num
修改sql
String sql = "update goods set num = num -1 where id = 1 and num>0 for update ";