【发布时间】:2020-02-22 07:05:25
【问题描述】:
这是我对 CPU 和线程的基本理解(天真!)。处理器每个内核可以运行一个线程。
我的笔记本电脑上的系统信息如下所示
处理器 Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz, 2112 Mhz, 4 Core(s), 8 Logical Processor(s)
**可以并行运行8个线程**
为了验证我的理解,我创建了一个 Spring Boot(嵌入式 tomcat)来处理每个请求
@GetMapping("/ping")
public String ping(@RequestParam String id) throws InterruptedException {
System.out.println(MessageFormat.format("The request id is {0}", id));
int i = Integer.parseInt(id);
long now = System.currentTimeMillis();
long period = 5000L;
long later = System.currentTimeMillis();
if (i % 2 == 1) {
while (later - now <= period) {
later = System.currentTimeMillis();
}
}
return PING_SUCCESSFUL;
}
我还将tomcat上的最大线程数设置为以下
server.tomcat.max-threads=200
我现在使用 Apache JMeter 在 1 秒内触发 200 个请求
我的期望是我的系统只能运行 8 个线程,因此请求的总运行时间应至少为 (200 / 8)*5 = 125 秒
然而,即使是 125 秒也是不现实的,因为我的系统上运行着其他应用程序,例如 Browser、JMeter、IntelliJ,它们本身应该考虑一些线程。
我观察到一个对比的行为 - 观察到的总运行时间是 5 秒。 这怎么可能让系统运行超过限制的线程数? (我发现对线程以及底层处理器如何并行化线程有一些理解错误)
【问题讨论】:
-
JVM 线程是 1::1 与 OS 线程,但这些不是 1::1 与处理器线程,这是你真正要问的。任何处理器线程都可以被抢占或重新调度以等待它在某些外部事件(例如 I/O 完成)上被阻塞。
标签: java multithreading processor