TestNG优雅地终止了线程。有任何想法为什么?

huangapple go评论55阅读模式
英文:

TestNG gracefully kills the thread. Any idea why?

问题

以下是您提供的内容的翻译:

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

@Test
public void testThreads(){
    new Thread(() -> {
        System.out.println("这个会被打印");
        try {
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("这个不会被打印");
    }).start();
}

这里的输出只是 这个会被打印,而第二行被忽略了。没有抛出异常。然而,如果我这样做:

public static void main(String[] args) {
    new Thread(() -> {
        System.out.println("这个会被打印");
        try {
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("这个不会被打印");
    }).start();
}

两行都如预期般被打印出来。您能解释一下为什么会出现这种奇怪的行为吗?

英文:

I'm using TestNG version 7.1.0 and this is my sample code:

@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();
}

The output here is just This is printed while the second line is ignored. No exception is thrown. However if I'm doing this:

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();
}

Both lines are printed as expected. Can you please explain why that strange behavior is observed?

答案1

得分: 1

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

英文:

TestNG uses a call to System.exit to execute your test case. That will terminate your started thread. If you add a clearly longer wait than 100 millis at the end of your test method, after you have started the explicit thread, you will see the second print statement.

huangapple
  • 本文由 发表于 2020年10月4日 03:44:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64188324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定