使用单元测试模拟多线程高并发访问接口,代码如下:
@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);
}
}
以上代码也可以输出结果,为什么?
主线程在初始化完10个子线程后就已经关闭了,当主线程关闭子线程也会随着关闭,如果你想看到效果 可以在for后面休眠一段时间阻塞 主线程