Processes & Threads

Multitasking: A CPU core performs context switching, i.e. switches to a different task while waiting for things like I/O (core can only perform one task at a time) Parallelism: Multiple processes are executed at the same time across diff CPU cores Concurrency: Multiple processes are active at the same time, though not necessarily in parallel.

Processes

  • Managed by OS.
  • Each process has own memory space. No cross process memory access Inter process communication (IPC)
  • Saved in process table with process control blocks (PCB)
    • Each time context switch: capture PCB of blocked process, load PCB of new process

Threads

  • Each process can contain many threads.
  • Managed by user (like Java Threads library)
  • Can communicate directly via shared memory
    • Same heap, different stack and instruction stream
    • No capture or loading of PCB (very low overhead)

JVM maps to kernel-level threads, which are managed by OS

CPU-level thread Enables execution of mult threads simultaneously on physical cores (hyperthreading) Uses fact that CPU core contains different types of processing unites

class Sum extends Thread {
    private int start;
    private int end;
    private int[] nums;
    private int result;
    
    public Sum(int start, int end, int[] nums) {
        this.start = start;
        this.end = end;
        this.nums = nums;
    }
    
    @Override
    public void run() {
        result = 0;
        for (int i = start; i <= end; i++)
            result += nums[i];
    }
    
    public int getResult() {
        return result;
    }
}
 
class Main {
    public static void main(String[] args) throws InterruptedException {
        int[] nums = new int[100_000];
        Arrays.fill(nums, 1);
 
        int chunkSize = 100;
        int numThreads = nums.length / chunkSize;
        Sum[] threads = new Sum[numThreads];
        
        // Create and start all threads
        for (int i = 0; i < nums.length; i += chunkSize) {
            Sum t = new Sum(i, i + chunkSize - 1, nums);
            threads[i / chunkSize] = t;
            t.start();
        }
        
        // Wait for all threads to finish, then collect results
        long totalSum = 0;
        for (Sum t : threads) {
            t.join();
            totalSum += t.getResult();
        }
        
        System.out.println("Total sum: " + totalSum); // Expected: 100_000
    }
}