【问题标题】:Running multiple threads from within a unit test从单元测试中运行多个线程
【发布时间】:2014-12-02 10:35:41
【问题描述】:

下面是一个单元测试,它使用 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();
            }
        }
    }

}

RequestThread 中的行 System.out.println("in RequestThread"); 似乎没有被调用,因为没有输出显示到控制台。 我认为问题在于,由于测试运行完成,它会导致scheduler 停止调度?是否可以更新测试以使scheduler 不会终止并且每秒重复调用一次RequestThreadInvoker

RequestThreadInvoker 中,我创建了一个ExecutorService 的新实例。这会导致问题吗?

【问题讨论】:

    标签: java multithreading unit-testing junit


    【解决方案1】:

    Thread.sleep(99000); 添加到测试结束会导致测试等待 99 秒,这足以让测试运行。

    【讨论】:

      【解决方案2】:

      您需要在线程池运行时阻塞主测试线程(睡眠/等待)。要从一个单独的线程执行断言,您可以使用 concurrentunit 之类的东西。

      【讨论】:

        猜你喜欢
        • 2010-09-30
        • 2014-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多