• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

Modern CPUs have multiple cores, but traditional single-threaded programs use only one. Without concurrent execution, applications cannot utilize available hardware, respond to user input while processing data, or handle multiple network connections simultaneously.

Core Idea

Multithreading allows concurrent execution of two or more threads within the same program. Each thread has its own stack and program counter but shares the heap. Java provides two ways to create threads: extending the Thread class or implementing the Runnable interface. Java also provides Callable, Future, and the Executor framework for advanced concurrency.

How It Works

When a Java program starts, the JVM creates the main thread. Additional threads can be created and started. The operating system’s thread scheduler allocates CPU time to threads (preemptive multitasking). Threads can be in various states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED.

Visual Explanation

java_threads Main Main Thread T1 Thread 1 (Database Query) Main->T1 thread.start() T2 Thread 2 (UI Update) Main->T2 T3 Thread 3 (File Download) Main->T3 CPU CPU Cores T1->CPU Share Shared Heap (Objects, Data) T1->Share T2->CPU T2->Share T3->CPU T3->Share

Semantic Network

semantic_multithreading THIS Multithreading SYNC Synchronization THIS--SYNC builds into EXEC Executor Framework THIS--EXEC builds into LAMB Parallel Streams THIS--LAMB builds into MEM Memory Management THIS--MEM related

Key Properties

  • Thread creation: Extend Thread (override run()) or implement Runnable (pass to Thread)
  • Daemon threads: Low-priority background threads that don’t prevent JVM exit
  • Thread priority: 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY) — hints to the scheduler
  • Thread.sleep(): Pauses the current thread without releasing locks

Connections

Edge Cases & Gotchas

  • Thread.start() vs run(): start() creates a new thread; run() executes in the current thread
  • Race conditions: Multiple threads reading/writing shared data without synchronization
  • Visibility issues: Changes by one thread may not be visible to others without happens-before guarantees
  • Daemon threads terminated abruptly: Daemon threads are killed when no user threads remain