问题描述
@Slf4j
@RestController
public class DemoController {
@GetMapping
public String testStr(String str) {
String key = UUID.randomUUID().toString();
log.info("testStr start {} {}",str,key);
synchronized (str.intern()) {
log.info("testStr in {} {}",key);
Thread.sleep(5000);
}
log.info("testStr end {} {}",key);
return str;
}
}
当我调用两个请求 ?str=aaa
时,日志如下所示:
testStr start aaa 3bbb03e3-84d9-4816-b275-de59657bd810
testStr in aaa 3bbb03e3-84d9-4816-b275-de59657bd810
... after 5 sec
testStr end aaa 3bbb03e3-84d9-4816-b275-de59657bd810
testStr start aaa b4f07a65-e37e-4471-be79-877a8d529f04
testStr in aaa b4f07a65-e37e-4471-be79-877a8d529f04
... after 5 sec
testStr end aaa b4f07a65-e37e-4471-be79-877a8d529f04
但我觉得应该是
testStr start aaa 3bbb03e3-84d9-4816-b275-de59657bd810
testStr in aaa 3bbb03e3-84d9-4816-b275-de59657bd810
testStr start aaa b4f07a65-e37e-4471-be79-877a8d529f04
... after 5sec
testStr in aaa b4f07a65-e37e-4471-be79-877a8d529f04
testStr end aaa 3bbb03e3-84d9-4816-b275-de59657bd810
... after 5 sec
testStr end aaa b4f07a65-e37e-4471-be79-877a8d529f04
不同部分:testStr start...
应该在 5 秒之前记录。
我错过了什么吗?
顺便说一句,我用简单的 main 测试了这些代码,没有 spring 的东西,然后一切都按预期工作。
主要代码
public static void main(String[] args) {
DemoController demoController = new DemoController();
new Thread(()->{
String result = demoController.testStr("aaa");
log.info("result1 {}",result);
}).start();
new Thread(()->{
String result = demoController.testStr("aaa");
log.info("result2 {}",result);
}).start();
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)