目标:我想要验证一下继承Thread创建的后台线程是否正常运行。

结论:
1、使用junit单元测试创建的后台线程(也就是非守护线程),JVM进程会在执行完单元测试代码后立即退出;
2、使用普通main函数创建的后台线程,JVM会等待后台线程结束;
3、由此得出,常规的单元测试函数,不适合测试多线程逻辑;

public class CreateThreadWithExtendsThread extends Thread {

    @Override
    public void run(){
        while(true){
            System.out.println("Thread is running, Thread name is " + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

// 单元测试
@Test
void contextLoads() throws InterruptedException {
    CreateThreadWithExtendsThread createThreadWithExtendsThread = new CreateThreadWithExtendsThread();
    createThreadWithExtendsThread.start();
}

运行结果是:

C:\Users\ourenjiang\.jdks\corretto-17.0.19\bin\java.exe "...
Thread is running, Thread name is Thread-0

进程已结束,退出代码为 0

如果是通过普通main来测试:

public static void main(String[] args) {
    CreateThreadWithExtendsThread createThreadWithExtendsThread = new CreateThreadWithExtendsThread();
    createThreadWithExtendsThread.start();
}

运行结果是符合预期的:

C:\Users\ourenjiang\.jdks\corretto-17.0.19\bin\java.exe "...
Thread is running, Thread name is Thread-0
Thread is running, Thread name is Thread-0
Thread is running, Thread name is Thread-0
Thread is running, Thread name is Thread-0

进程已结束,退出代码为 130

如果你直的不想写main函数,可以手动join线程,从而达到阻塞主线程的作用

// 单元测试
@Test
void contextLoads() throws InterruptedException {
    CreateThreadWithExtendsThread createThreadWithExtendsThread = new CreateThreadWithExtendsThread();
    createThreadWithExtendsThread.start();
}
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐