1. 程式人生 > 其它 >Junit 使用 CountDownLatch 多執行緒測試

Junit 使用 CountDownLatch 多執行緒測試

技術標籤:JavaSpring bootSpringjava

package com.lgq.demo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.test.context.ActiveProfiles;

import java.util.
concurrent.CountDownLatch; import java.util.concurrent.ThreadPoolExecutor; /** * 多執行緒測試 * * @Author: guanqin_li * @Date: 2021-02-18 10:39 */ @SpringBootTest @ActiveProfiles("dev") public class ThreadTest { @Test public void test() throws InterruptedException { ThreadPoolTaskExecutor executor =
new ThreadPoolTaskExecutor(); executor.setThreadNamePrefix("thread-pool-"); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); executor.setKeepAliveSeconds(300); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.
CallerRunsPolicy
()); executor.setWaitForTasksToCompleteOnShutdown(true); executor.initialize(); // 任務總數 final int total = 20; CountDownLatch countDownLatch = new CountDownLatch(total); System.out.println("=========start======="); for (int i = 0; i < total; i++) { executor.execute(() -> { try { //TODO 業務處理 System.out.println(Thread.currentThread().getName() + "|" + countDownLatch.getCount()); } catch (Exception e) { e.printStackTrace(); } finally { // 很關鍵, 無論上面程式是否異常必須執行countDown,否則await無法釋放 countDownLatch.countDown(); } }); } // 所有執行緒countDown()都執行之後才會釋放當前執行緒,程式才能繼續往後執行 countDownLatch.await(); //關閉執行緒池 executor.shutdown(); System.out.println("=========finished======="); } }

執行結果:

2021-02-18 10:50:07.000  INFO 115072 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService
=========start=======
thread-pool-1|20
thread-pool-1|19
thread-pool-1|18
thread-pool-1|17
thread-pool-1|16
thread-pool-1|15
thread-pool-1|14
thread-pool-1|13
thread-pool-1|12
thread-pool-1|11
thread-pool-1|10
thread-pool-1|9
thread-pool-1|8
thread-pool-1|7
thread-pool-1|6
thread-pool-1|5
thread-pool-2|4
thread-pool-3|4
thread-pool-4|2
thread-pool-5|1
2021-02-18 10:50:07.006  INFO 115072 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService
=========finished=======