线程在 JUnit 中的行为异常 [英] Thread behaving strangely in JUnit

查看:30
本文介绍了线程在 JUnit 中的行为异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个需要多线程的单元测试.但是,线程似乎只是在执行过程中停止了.考虑以下代码:

I'm trying to write a unit test that requires mulitple threads. However, it seems that the threads just stop part way through execution. Consider the following code:

public class Test {
    @org.junit.Test
    public void TestThreads() {
        new Thread(new Runnable() {
            public void run() {
                for (int i = 1; i < 1000; i++) System.out.println(i);
            }
        }).start();
    }
}

如果我运行这个单元测试,它通常会停止在 140-180 之间的某个地方显示输出.如果我将此代码转换为常规类并运行它,它就可以正常工作.有人知道我在这里缺少什么吗?

If I run this unit test, it will generally stop displaying output somewhere between 140-180. If I convert this code into a regular class and run it, it works fine. Does anybody have any idea what I'm missing here?

谢谢,- 安德鲁.

推荐答案

您可以使用 Thread.join() 来防止测试在新线程完成其任务之前完成:

You can use Thread.join() to prevent the test from finishing before the new thread has completed its task:

@org.junit.Test
public void TestThreads() throws InterruptedException {
    Thread t = new Thread(new Runnable() {
        public void run() {
            for (int i = 1; i < 1000; i++) System.out.println(i);
        }
    });
    t.start();
    t.join();
}

通常,JVM 会在最后一个非守护线程终止时终止.您可能希望在线程上简单地调用 t.setDaemon(false) 会阻止 JVM 在任务完成之前退出.但是,junit 会调用 System.exit() 当主线程完成时.

Normally, the JVM will terminate when the last non-daemon thread terminates. You might expect that simply calling t.setDaemon(false) on the thread would prevent the JVM from exiting before the task is finished. However, junit will call System.exit() when the main thread has finished.

Gus 在评论中指出:你需要 join() 因为 start() 不会阻塞".

As Gus notes in the comments: "you need join() because start() doesn't block".

他说得对,您也可以在这个最小示例中调用 run().但是,我假设您正在启动一个线程,因为您希望它与另一个线程同时运行.FindBugs 将在线程上调用 run() 标记为可能的错误 - 如果您只想调用 run(),您可能只想实现 Runnable 而不是使用 Thread.

He's correct that you could also call run() in this minimal example. However, I assume you're starting a thread because you want it to run concurrently with another thread. Calling run() on a Thread is flagged up as a possible mistake by FindBugs - if you're just going to call run(), you'd probably just want to implement Runnable instead of using Thread.

这篇关于线程在 JUnit 中的行为异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆