原因:
JUnit 测试框架并不会等待你的线程完成。当测试方法结束时,JUnit 认为测试已经完成,即使线程仍在运行。
解决方案
1.使用 Thread.join()
- 在测试方法中启动线程后,使用
thread.join()
明确等待线程完成。 - 示例:
@Test public void test() throws InterruptedException { Thread thread1 = new Thread(() -> { // 线程1的代码 }); thread1.start(); thread1.join(); // 等待线程1完成 Thread thread2 = new Thread(() -> { // 线程2的代码 }); thread2.start(); thread2.join(); // 等待线程2完成 // 进行断言验证 }
什么是断言验证?https://blog.csdn.net/m0_61160520/article/details/141322577?spm=1001.2014.3001.5501
2.使用 CountDownLatch
- 使用
CountDownLatch
来确保所有线程完成后再进行验证。 - 示例:
@Test public void test() throws InterruptedException { CountDownLatch latch = new CountDownLatch(2); // 两个线程 new Thread(() -> { // 线程1的代码 latch.countDown(); // 减少计数器 }).start(); new Thread(() -> { // 线程2的代码 latch.countDown(); // 减少计数器 }).start(); latch.await(); // 等待所有线程完成 // 进行断言验证 }
3.使用 JUnit 的 Timeout
- 使用
@Test(timeout = 1000)
设置测试的最大执行时间,确保测试不会无限期地等待。 - 示例:
@Test(timeout = 1000)
public void test() throws InterruptedException {
Thread thread1 = new Thread(() -> {
// 线程1的代码
});
thread1.start();
thread1.join(); // 等待线程1完成
Thread thread2 = new Thread(() -> {
// 线程2的代码
});
thread2.start();
thread2.join(); // 等待线程2完成
// 进行断言验证
}