TestNG 优雅地终止线程。知道为什么吗?

TestNG gracefully kills the thread. Any idea why?

我使用的是 TestNG 版本 7.1.0,这是我的示例代码:

@Test
public void testThreads(){
    new Thread(() -> {
        System.out.println("This is printed");
        try {
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("This is not printed");
    }).start();
}

这里的输出只是This is printed,而第二行被忽略了。不会抛出异常。但是,如果我这样做:

public static void main(String[] args) {
    new Thread(() -> {
        System.out.println("This is printed");
        try {
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("This is not printed");
    }).start();
}

两行都按预期打印。你能解释一下为什么会出现这种奇怪的行为吗?

TestNG 使用对 System.exit 的调用来执行您的测试用例。这将终止您启动的线程。如果您在测试方法的末尾添加一个明显长于 100 毫秒的等待时间,则在启动显式线程后,您将看到第二个打印语句。