简体   繁体   English

JVM 线程的概念以及与 OS 线程的关系

[英]Concept of JVM thread and relation to OS thread

Here is my fundamental understanding of the CPU and threads(naive!).这是我对 CPU 和线程的基本理解(天真!)。 The processor can run one thread per core.处理器每个内核可以运行一个线程。
System information on my laptop reads as show below我的笔记本电脑上的系统信息如下所示
Processor Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz, 2112 Mhz, 4 Core(s), 8 Logical Processor(s) **Can run 8 threads in parallel **处理器 Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz, 2112 Mhz, 4 Core(s), 8 Logical Processor(s) **可以并行运行 8 个线程 **
In order to validate my understanding i create a Spring Boot(embedded tomcat) to handle each request为了验证我的理解,我创建了一个 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;

} }

I also set the max threads on tomcat to the following我还将 tomcat 上的最大线程数设置为以下

server.tomcat.max-threads=200 server.tomcat.max-threads=200

I now use Apache JMeter to trigger 200 requests in a duration of 1 seconds我现在使用 Apache JMeter 在 1 秒内触发 200 个请求

My expectation is my system is constrained to run only 8 threads and hence the total run time of the requests should be at least (200 / 8)*5 = 125 seconds我的期望是我的系统只能运行 8 个线程,因此请求的总运行时间应该至少为(200 / 8)*5 = 125 秒
However even the 125 seconds is not realistic as there are other applications running on my system like Browser, JMeter, IntelliJ which should account for some threads themselves.然而,即使是 125 秒也是不现实的,因为我的系统上还有其他应用程序在运行,比如浏览器、JMeter、IntelliJ,它们应该自己考虑一些线程。

I observe a contrasting behavior - the total runtime observed is 5 seconds .我观察到一个对比行为 - 观察到的总运行时间为5 秒 How is this possible for the system to run more threads than the limit?系统怎么可能运行超过限制的线程数? ( I find some understanding amiss about the threads and how the underlying processors seem to paralelize the threads) (我发现对线程以及底层处理器似乎如何并行化线程有一些理解错误)

It is true that the system can run only 8 threads simultaneously, but the operating system schedules which of the eight are running at any given time and can both preempt andtime slice processes to schedule other (waiting) processes for some portion of time.确实,系统只能同时运行 8 个线程,但操作系统会调度 8 个线程中的哪一个在任何给定时间运行,并且可以抢占时间片进程来调度其他(等待)进程一段时间。 Java threads are isomorphic to native threads, so it's literally the operating system scheduling them (and if your computer worked like you thought, the network would stop working while your program ran). Java 线程与本机线程同构,因此实际上是操作系统调度它们(如果您的计算机像您想象的那样工作,则网络将在您的程序运行时停止工作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM