JUnit test not executing all threads created within the test

孤街醉人 提交于 2019-11-29 13:53:56

JUnit is exiting the test method early. You need to wait for all of the threads to complete before you exit the testCalculator() method.

An easy way to do that is by using a CountDownLatch.

  1. Initialize a CountDownLatch with CountDownLatch latch = new CountDownLatch(20).

  2. Pass each Calculator runnable a reference to the latch. At the end of the run() method, call latch.countDown().

  3. At the end of the testCalculator() method call latch.await(). This will block until latch.countDown() has been called 20 times (i.e. when all threads have completed).

Your test method finishes before all the spawned threads are finished. When the JUnit executor finishes, all spawned threads are killed.

If you want to run this kind of test, you should keep a collection of the threads you have created and join() each of them at the end of your test method. The calls to join() each thread are executed in a second loop (following the loop that starts all the threads).

Something like this:

@Test
public void testCalculator() {
    List<Thread> threads = new ArrayList<>();
    for (int i = 1; i < 21; i++) {
        calculator = new Calculator(i);
        thread = new Thread(calculator);
        threads.add(thread);
        System.out.println(thread.getName() + " Created");
        thread.start();
        System.out.println(thread.getName() + " Started");
    }
    for (Thread thread : threads) {
        thread.join();
    }
 }

If you want to have the threads all start around the same time (e.g., if your loop that is creating the threads does some non-trivial work each time through the loop):

@Test
public void testCalculator() {
    List<Thread> threads = new ArrayList<>();
    for (int i = 1; i < 21; i++) {
        threads.add(new Thread(new Calculator(i)));
    }
    for (Thread thread : threads) {
        thread.start();
    }
    for (Thread thread : threads) {
        thread.join();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!