简体   繁体   English

在单元测试中运行多个线程

[英]Running multiple threads from within a unit test

Below is a unit test which uses ScheduledExecutorService to execute a scheduled runnable every second : 下面是一个使用ScheduledExecutorService每秒执行一个调度的可运行对象的单元测试:

   import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class ConcurrentRequestSimulator {

    private static final int NUMBER_REQUESTS = 4;

    @Test
    public void testGetToDoList() {

        try {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
            scheduler.scheduleAtFixedRate(new RequestThreadInvoker(), 0, 1, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final class RequestThreadInvoker implements Runnable {

        public void run() {

            ExecutorService es = Executors.newCachedThreadPool();
            for (int i = 1; i <= NUMBER_REQUESTS; i++) {
                es.execute(new RequestThread());
            }
            es.shutdown();

            while (!es.isTerminated()) {

            }

        }
    }

    private final class RequestThread implements Runnable {

        public void run() {
            try {
                System.out.println("in RequestThread");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

The line System.out.println("in RequestThread"); System.out.println("in RequestThread"); in RequestThread does not appear to be invoked as no output is displayed to console. RequestThread似乎没有被调用,因为没有任何输出显示到控制台。 I think the issue is that since the test runs to completion, it causes the scheduler to stop scheduling? 我认为问题在于,既然测试运行完毕,就会导致scheduler停止调度? Can the test be updated so that scheduler is not terminated and RequestThreadInvoker is invoked repeatedly once per second ? 是否可以更新测试,以便不终止scheduler并且每秒重复调用一次RequestThreadInvoker

In RequestThreadInvoker I create a new instance of ExecutorService . RequestThreadInvoker我创建一个ExecutorService的新实例。 Could this be causing the issue ? 这可能是造成问题的原因吗?

Adding Thread.sleep(99000); 添加Thread.sleep(99000); to end of test causes test to wait 99 seconds which is enough time for test to run. 到测试结束会使测试等待99秒,这足以运行测试。

You'll need to block the main test thread (sleep/wait) while the thread pools are running. 您需要在线程池运行时阻止主测试线程(睡眠/等待)。 To perform assertions from one of the separate threads you can use something like concurrentunit . 为了从单独的线程,你可以使用类似的一个执行断言concurrentunit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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