线程在JUnit中表现奇怪 [英] Thread behaving strangely in JUnit

查看:92
本文介绍了线程在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?

谢谢,
- 安德鲁。

Thanks, - Andrew.

推荐答案

您可以使用 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在评论中所说:你需要加入(),因为启动()不会阻止。

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

他是正确的,你也可以在这个最小的例子中调用 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天全站免登陆