如果在 jUnit 测试中,为什么非守护线程会终止?

2022-01-16 00:00:00 multithreading daemon jvm spring java

以下 daemon-bean 正在运行:

The following daemon-bean is running:

public class DaemonBean extends Thread {

    private final static Logger log = LoggerFactory.getLogger(DaemonBean.class);

    {
        setDaemon(true);
        start();
    }

    @Override
    public void run() {

        for(int i=0; i<10 && !isInterrupted(); ++i) {
            log.info("Hearbeat {}", i);
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                return;
            }
        }

    }
}

它是守护进程,所以如果单例会终止.

It is daemon, so would terminate if singleton.

所以,下面的非守护进程 bean 正在等待他:

So, the following non-daemon bean is waiting for him:

public class Waitor1 extends Thread {

    private final static Logger log = LoggerFactory.getLogger(Waitor1.class);

    private Thread joinable;

    {
        setDaemon(false);
        setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread t, Throwable e) {
                log.error("Error in thread", e);
            }
        });
    }

    public Thread getJoinable() {
        return joinable;
    }

    public void setJoinable(Thread value) {
        this.joinable = value;
        if( this.joinable != null ) {
            start();
        }
    }

    @Override
    public void run() {

        log.info("Waiting started");

        try {
            joinable.join();
        } catch (InterruptedException e) {
            log.info("Thread interrupted");
            return;
        }

        log.info("Waiting ended");

    }

}

bean 的 Spring 配置是:

The Spring configuration for beans is:

<bean id="daemon" class="beans.DaemonBean"/>

    <bean id="waitor" class="beans.Waitor1">
        <property name="joinable" ref="daemon"/>
    </bean>

问题是:为什么从 main 运行它可以工作,而如果从 jUnit 测试运行它却不工作?

The question is: why is it working if runned from main and not working if ran from jUnit test?

运行代码是

 public static void main(String[] args) {
        new ClassPathXmlApplicationContext("/beans/Waiting1.xml");
    }

@Test
    public void testWaiting1() {
        new ClassPathXmlApplicationContext("/beans/Waiting1.xml");
    }

在 main 的情况下,我看到所有的心跳.在 jUnit 的情况下,我只看到心跳 0,然后消息等待开始"并且程序终止,就好像没有人在这里等待非守护线程一样.

In case of main I see all hearbeats. In case of jUnit I see only heartbeat 0, then message "Waiting started" and the program is terminated as if nobody waiting for non-daemon threads here.

这可能是什么原因?

推荐答案

当您从 main 运行代码时,它会创建两个 bean,因此会创建两个线程 - 守护进程和非守护进程.只要非守护线程正在运行,您的应用程序就不会退出.所以它起作用了.

When you run your code from main it creates both beans, thus two threads - daemon and non-daemon. As long as non-daemon thread is running, your application won't exit. So it works.

从 JUnit 运行时不同.一旦 JUnit 测试方法完成(并且它在 Spring 上下文启动后立即完成),JUnit 就会假定您的测试已经完成.因此它会杀死你所有的线程,基本上是整个 JVM.

It's different when run from JUnit. As soon as JUnit test method completes (and it completes immediately after the Spring context is up), JUnit assumes your tests are done. Thus it kills all your threads and basically the whole JVM.

记住你的 Waitor1 bean 会产生一个 JUnit 不关心的后台线程.一旦你离开 @Test 方法,JUnit 就会停止一切.

Remember your Waitor1 bean spawns a background thread which JUnit doesn't care about. As soon as you leave @Test method JUnit will just stop everything.

相关文章