Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 验证并发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);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement