前言
在知乎看到这么一个提问:在springboot的controller中使用Thread.sleep,为什么不能并行执行?
如代码所示,在controller的sleep方法中,使用了 Thread.sleep,然后用chrome打开两个页签模拟并行访问,发现这两次请求是串行执行的。第二次请求需要等待第一次请求执行完毕才可以:
-
package com.kfit.controller;
-
import org.springframework.web.bind.annotation.RequestMapping;
-
import org.springframework.web.bind.annotation.RestController;
-
@RestController
-
public class AsyncController {
-
@RequestMapping("async")
-
public String sleep() throws InterruptedException {
-
long startTime = System.currentTimeMillis();
-
System.out.println("[before]name is " + Thread.currentThread().getName() + " time is " + startTime);
-
Thread.sleep(10000);
-
long endTime = System.currentTimeMillis();
-
System.out.println("[after]name is " + Thread.currentThread().getName() + " time is " + endTime + " cos " + (endTime-startTime));
-
return Thread.currentThread().getName();
-
}
-
}
控制台输出如下:
[之前]名称是1602751326997
[后]名称 1602751337000是
[之前]名称是1602751337004
[后]名称是 19-8080-exec-3 时间是 1602751347008 cos10004
为什么不能并行执行?按照我的理解,多个http请求到达controller的时候,是不同的线程进行处理的。照理说应该是可以并行的。
这个和我对于这个多线程的认知结果不太一样,于是好奇心作祟,就试了下,结果还真是串行执行呐。这个是为什么呢?如果你也有我和一样的疑问,本文为你解惑。
一、准备工作
为了模拟上面的场景,我们需要创建一个SpringBoot项目,这个步骤略过,如果还有不懂的小盆友,那么你得看看SpringBoot的helloworld了。
1.1 环境说明
。。。。。。。。。。。。。。。。。
版权原因,完整文章,请参考如下:SpringBoot的controller为什么不能并行执行?同一个浏览器连续多次访问同一个url竟然是串行的?- 第329篇