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.
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.
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");
}
}Running in a thread
Main finishedA 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.
