简体   繁体   中英

How do I test the completion of threads created under my testmethod in JUnit

I have a method createThreads which spawns few new threads. Each of the newly created thread does some work. If I invoke the method `createThreads' in junit, how can i ensure that all the newly spawned threads have also completed successfully.

I am currently calling as below

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

Note that I cannot modify createThreads

a bit odd but..

you can probably get all the runing threads

through Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); then filter it to identify the thread from the executor service. then do a .join() on each of those threads.

as i said, a bit odd but it should fit your needs ...

try running this, you'll see that they are quite easy to identify :

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

}

sorry for a 2nd answer not possible to add such a long code in comment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM