使用单元测试模拟多线程高并发访问接口

使用单元测试模拟多线程高并发访问接口,代码如下:

@Test
public void findCityByName1() throws Exception {
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                City city = cityService.findCityByName("温岭市");
                System.out.println(city);
            }
        });
    }
}
City city = cityService.findCityByName("温岭市");
System.out.println(city);

上述代码是通过访问数据库获取数据,运行单元测试没有任何输出。但是如果把访问数据库的代码改成直接输出,如:
System.out.println("测试");则可以输出结果。

或者在访问数据库的代码中加上Thread.sleep(100);,代码如下:

@Test
public void findCityByName1() throws Exception {
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                City city = cityService.findCityByName("温岭市");
                System.out.println(city);
            }
        });
        Thread.sleep(100);
    }
}

以上代码也可以输出结果,为什么?

阅读 12.1k
2 个回答

主线程在初始化完10个子线程后就已经关闭了,当主线程关闭子线程也会随着关闭,如果你想看到效果 可以在for后面休眠一段时间阻塞 主线程

因为在JUnit测试框架中,主线程退出,子线程也会退出,由于子线程执行findCityByName的耗时较长,所以在没有打印结果之前就退出了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题