CPU and Java Threads
CPU and Cores
The full name of CPU is central Processing Unit. A Modern CPU typically has multiple cores. Each core can be considered as independent processor.
A CPU Thread (Virtual Core) is hardware-level virtual versions of a CPU core which is a sequence of instructions that can be executed independently by a processor.
Multiple Process / Multitasking
For a single core, the fact is only one process can be executed at any one time on a single core CPU. To achieve multiple tasking, the operating system (OS) would use some techniques like process switching (context switching) to make multiple simultaneously executing process happen.
Java Threads
A Java thread is execution unit in JVM. JVM enable a Java application to have multiple concurrently running threads. Java Threads are managed in JVM by task scheduling for concurrent processing.
Multiple Threads and CPU
In Java Memory Model, there are two important memory components which is Heap and Stack.
Heap is a memory area for Java objects while Stack is a memory area for each Thread.
JVM enable multiple threads on different CPUs. Each Thread has its own local memory area (Stack) to store the temporal computation results. Once the thread completes its execution, it will flushes the result back to RAM (Heap).
Therefore, the variables accessed by different threads may be different. Java provides a keyword volatile
to tell the thread need to read the latest value of the variables in the main memory.