使用@Test测试线程时会立马结束的问题

原因:

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完成
    
        // 进行断言验证
    }

什么是断言验证?icon-default.png?t=N7T8https://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完成

    // 进行断言验证
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值