Advertisement
Guest User

Untitled

a guest
Feb 20th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. /**
  2. * 验证并发update mysql数据库记录
  3. * @param args
  4. * @throws SQLException
  5. * @throws IOException
  6. * @throws InterruptedException
  7. */
  8. public static void main(String[] args) throws SQLException, IOException, InterruptedException {
  9. String url = "jdbc:mysql://localhost:3306/test";
  10. String user = "root";
  11. String password = "123456";
  12.  
  13. int nThreads = 140; //不要超过数据库最大连接数 : max_connections 151
  14. ExecutorService pool = Executors.newFixedThreadPool(nThreads);
  15. CountDownLatch startLatch = new CountDownLatch(nThreads);
  16. CountDownLatch endLatch = new CountDownLatch(nThreads);
  17.  
  18. for (int i = 0; i < nThreads; i++) {
  19. pool.submit(() -> {
  20. startLatch.countDown();
  21. try { startLatch.await(); } catch (Exception e1) { } //等待所有任务都提交了再往下执行 保证并发
  22.  
  23. String sql = "update t set count = count-1 where id =1 and count>0";
  24. try {
  25. Connection connection = DriverManager.getConnection(url, user, password);
  26. Statement stat = connection.createStatement();
  27. stat.execute(sql);
  28. endLatch.countDown();
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. });
  33. }
  34. endLatch.await(); //等待所有的任务都完成
  35. System.out.println("done");
  36. System.exit(0);
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement