Java多线程测试执行时长

可以使用CountDownLatch ,指定线程数量。 当latch调用await时阻塞,直到所有的线程都执行latch.countDown(); 例如下面的例子,300个线程

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    @Test  
    public void testIdWorker() throws InterruptedException {  
        int threadCount = 300;  
        //latch.await()等待300个线程都执行完成countDown后,才能继续执行  
        CountDownLatch latch = new CountDownLatch(threadCount);  
  
        Runnable task = ()-> {  
            for (int i = 0; i < 100; i++) {  
                long l = redisIdWorker.nextId("order");  
                System.out.println(l);  
            }  
            // 每个任务都要countDown  
            latch.countDown();  
        };  
        long begin = System.currentTimeMillis();  
        for (int i = 0; i < threadCount; i++) {  
            es.submit(task);  
        }  
        latch.await();  
        long end = System.currentTimeMillis();  
        System.out.println("time=" + (end-begin));  
    }  
}

学习来源 https://www.bilibili.com/video/BV1cr4y1671t?p=49&vd_source=cdd8cee3d9edbcdd99486a833d261c72