如何阻止 Java SpringBoot Test 单元测试中包括多线程时,没跑完就结束了
使用 CountDownLatch
CountDownLatch、CyclicBarrier 使用区别
多线程 ThreadPoolTaskExecutor 应用
Java BasePooledObjectFactory 对象池化技术
@SpringBootTest
public class PoolTest {
@Test
void basePooledTest() throws InterruptedException {
AtomicInteger atomicInteger = new AtomicInteger();
int excutorCount = 15;
CountDownLatch countDownLatch = new CountDownLatch(excutorCount);
// =====================创建线程池=====================
ExecutorService excutor = Executors.newFixedThreadPool(5);
// =====================创建对象池=====================
// 对象池工厂
MqttConnectionFactory personPoolFactory = new MqttConnectionFactory();
// 对象池配置
GenericObjectPoolConfig<MqttConnection> objectPoolConfig = new GenericObjectPoolConfig<>();
objectPoolConfig.setMaxTotal(50);
// 对象池
GenericObjectPool<MqttConnection> mqttPool = new GenericObjectPool<>(personPoolFactory, objectPoolConfig);
// =====================测试对象池=====================
// 循环100次,从线程池中取多个多线程执行任务,来测试对象池
for (int i = 0; i < excutorCount; i++) {
excutor.submit(new Thread(() -> {
// 模拟从对象池取出对象,执行任务
MqttConnection mqtt = null;
try {
// 从对象池取出对象
mqtt = mqttPool.borrowObject();
// 让对象工作
int count = atomicInteger.addAndGet(1);
mqtt.publish("Id:" + count + " Time: " + DateUtil.now());
} catch (Exception e) {
e.printStackTrace();
} finally {
// 回收对象到对象池
if (mqtt != null) {
mqttPool.returnObject(mqtt);
}
countDownLatch.countDown();
}
}));
}
countDownLatch.await();
}
}