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=======