What is a thread?

Answer

A thread is the smallest unit of execution within a process — a lightweight process. Multiple threads within the same process share the same memory space (code, data, heap) but each has its own stack, program counter, and CPU registers. Thread vs process: threads share memory (no context-switch overhead for memory mapping), faster to create/destroy (no memory allocation), communicate easily (shared memory), but share risks (one thread crash can kill the process, data races). Processes are isolated (crash in one doesn't affect others, separate memory), safer but heavier. Thread components (own): stack (local variables, function calls), program counter (where it is in execution), CPU registers (current state). Thread components (shared with process): code segment, data segment (global vars), heap (dynamic memory), file descriptors, signals. Multithreading benefits: responsiveness (UI stays active while I/O happens), resource sharing (share data without IPC), economy (cheaper than processes), scalability (run on multiple CPUs simultaneously). Java threads: Thread t = new Thread(() -> { System.out.println("Thread: " + Thread.currentThread().getName()); }); t.start();. User-level threads vs kernel-level threads: user-level — managed by runtime library (fast, OS doesn't know about them, can't utilize multiple CPUs); kernel-level — managed by OS (slower, true parallelism on multicore). Modern OSes: M:N hybrid mapping.