Thread
A thread of execution that lets a program do several things at once.
Available since: Java 1.0
Syntax
public class Thread implements Runnable
public Thread(Runnable task)Parameters
| Parameter | Type | Description |
|---|---|---|
| task | Runnable | The code that runs in the new thread. |
Examples
Creating, starting and waiting for a thread:
void main() throws InterruptedException {
Thread worker = new Thread(() -> IO.println("Hello from " + Thread.currentThread().getName()));
worker.start();
worker.join();
IO.println("Back in " + Thread.currentThread().getName());
}Output:
Hello from Thread-0
Back in mainNotes
The task is passed as a Runnable lambda and started only with start(). Platform threads are expensive: thousands of them use a lot of memory. Modern code rarely creates threads by hand and uses an ExecutorService or virtual threads (Java 21) instead.
See also
- Thread.start() — Starts a thread: its code begins running in parallel with the caller.
- Thread.join() — Waits for a thread to finish.
- Thread.ofVirtual() — Creates a virtual thread — a lightweight thread you can start by the million.
- ExecutorService — A service that runs tasks on a pool of threads.
In the tutorial
- Threads — Threads in Java — the Thread class, starting with start, waiting with join, Thread.sleep, thread names and unpredictable execution order.