如何在JUnit中测试在testmethod下创建的线程的完成情况

时间:2014-04-02 08:41:39

标签: java multithreading junit

我有一个方法createThreads,它产生了很少的新线程。每个新创建的线程都可以完成一些工作。如果我调用`createThreads'在junit中,我如何确保所有新生成的线程也已成功完成。

我现在打电话如下

@Test
public void test() {
    createThreads();  // Does not wait until the newly created threads also finish.    
}


public void createThreads()
{
ExecutorService executorService = Executors
        .newFixedThreadPool(numThreads);
for (int i = 0; i < numThreads; i++) {
    executorService.execute(new Runnable() {
        @Override
        public void run() {
            try {
               Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("I have completed execution " + Thread.currentThread().getName());
        }
    });
}

请注意,我无法修改createThreads

2 个答案:

答案 0 :(得分:2)

有点奇怪但是......

你可能会获得所有正在运行的线程

通过Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); 然后过滤它以识别执行程序服务中的线程。 然后在每个线程上执行.join()。

正如我所说,有点奇怪,但它应该符合你的需要......

答案 1 :(得分:0)

尝试运行此功能,您会发现它们很容易识别:

public static void main(String[] args) {

    int nb = 3;
    ExecutorService executorService = Executors.newFixedThreadPool(nb);
    for (int i = 0; i < nb; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("I have completed execution " + Thread.currentThread().getName());
            }
        });

    }


    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    for (Thread t : threadSet) {
        System.out.println(t.getName());
    }

}

抱歉第二个答案无法在评论中添加如此长的代码

相关问题