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

Java 如何在JUnit中测试根据testmethod创建的线程的完成情况,java,multithreading,junit,Java,Multithreading,Junit,我有一个方法createThreads,它产生了一些新线程。每个新创建的线程都做一些工作。如果在junit中调用“createThreads”方法,如何确保所有新生成的线程也已成功完成 我现在打电话如下 @Test public void test() { createThreads(); // Does not wait until the newly created threads also finish. } public void createThreads() {

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

我现在打电话如下

@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();//不等待新创建的线程也完成。
}
public void createThreads()
{
ExecutorService ExecutorService=执行者
.newFixedThreadPool(numThreads);
for(int i=0;i
注意,我不能修改
createThreads

有点奇怪,但是

您可能会得到所有运行线程

通过
Set threadSet=Thread.getAllStackTraces().keySet();
然后对其进行过滤,以从executor服务中识别线程。 然后在每个线程上执行.join()


正如我所说,有点奇怪,但它应该适合您的需要…

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

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

}
publicstaticvoidmain(字符串[]args){
int nb=3;
ExecutorService ExecutorService=Executors.newFixedThreadPool(nb);
对于(int i=0;i

很抱歉,第二个答案不可能在注释中添加这么长的代码

将这些线程添加到列表中并检查它们是否已完成。请确保等到完成后才能访问ExecutorService?@Reddy我没有访问这些线程的权限。但我只知道正在创建一些线程。@user1121883:不,我有无法访问executor service,并且该方法不返回任何内容我无法访问executor service,因此无法筛选和识别此类线程