Java ยท Chapter 41 of 42

Java Threads & Concurrency

A thread is a lightweight unit of execution that can run concurrently with other threads. Java supports multithreading by extending Thread or implementing Runnable, and starting execution with start().

When multiple threads share data, you must synchronize access (using the `synchronized` keyword or concurrent utilities) to avoid race conditions.

Syntax
Thread t = new Thread(() -> {
  // code
});
t.start();

Creating threads

Implement Runnable and pass it to a Thread, or extend Thread directly and override run(). Call start() (not run()) to actually begin concurrent execution on a new thread.

Synchronization basics

The `synchronized` keyword ensures only one thread executes a block or method at a time, protecting shared data from race conditions.

Example 1 (java)
public class Main {
  public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread(() -> System.out.println("Running in a thread"));
    t.start();
    t.join();
    System.out.println("Main finished");
  }
}
Output
Running in a thread
Main finished

A lambda implementing Runnable runs on a new thread; join() waits for it to finish before continuing.

Key points

  • Threads allow concurrent execution of code.
  • start() begins a new thread; run() would just execute normally on the current thread.
  • synchronized protects shared data from race conditions.
  • join() waits for a thread to finish before continuing.
๐Ÿ’ก Note: Prefer higher-level concurrency utilities in java.util.concurrent over raw threads for complex real-world applications.

๐Ÿ“ Quick Quiz

1. Which method actually starts a new thread of execution?

2. What keyword helps prevent race conditions on shared data?

3. What does thread.join() do?