Skip to content

Instantly share code, notes, and snippets.

@zhugw
Created February 20, 2016 13:39
Show Gist options
  • Save zhugw/9e4b722f1ad5c626ca8a to your computer and use it in GitHub Desktop.
Save zhugw/9e4b722f1ad5c626ca8a to your computer and use it in GitHub Desktop.
验证并发更新库存
/**
* 验证并发update mysql数据库记录
* @param args
* @throws SQLException
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws SQLException, IOException, InterruptedException {
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
int nThreads = 140; //不要超过数据库最大连接数 : max_connections 151
ExecutorService pool = Executors.newFixedThreadPool(nThreads);
CountDownLatch startLatch = new CountDownLatch(nThreads);
CountDownLatch endLatch = new CountDownLatch(nThreads);
for (int i = 0; i < nThreads; i++) {
pool.submit(() -> {
startLatch.countDown();
try { startLatch.await(); } catch (Exception e1) { } //等待所有任务都提交了再往下执行 保证并发
String sql = "update t set count = count-1 where id =1 and count>0";
try {
Connection connection = DriverManager.getConnection(url, user, password);
Statement stat = connection.createStatement();
stat.execute(sql);
endLatch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
});
}
endLatch.await(); //等待所有的任务都完成
System.out.println("done");
System.exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment