Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Thread(Runnable) — construct a platform thread with a task

The `Thread(Runnable)` constructor creates a platform thread and associates it with a task without starting it. Use `start()` to launch the thread and `join()` to wait for it to finish.

Version: Java SE 21

Syntax

public Thread(Runnable task)

Thread worker = new Thread(task);

In Java SE 21, the Thread(Runnable) constructor of java.lang.Thread creates a new, unstarted platform thread with an automatically assigned name. A Runnable defines a task through its no-argument void run() method; you can pass an instance of a class such as Worker or a lambda. For an unstarted virtual thread, use Thread.ofVirtual().unstarted(task) with a non-null task.

start() schedules the task to run on the new thread. Calling run() directly on the object returned by new Thread(task) executes the task on the calling thread and is not a substitute for start(). Calling start() a second time on the same instance throws IllegalThreadStateException, even after it has terminated. Three calls to new Thread(task) create three distinct threads but share the task instance; make access to any shared mutable state thread-safe.

After start(), the no-argument join() waits for the thread to terminate. It can throw InterruptedException if the waiting thread is interrupted. After join() returns normally, the terminated thread's actions are visible to the thread that waited. A local variable captured by a lambda, such as a reference to a lock or a CountDownLatch, must be final or effectively final. Capturing the reference does not by itself provide synchronization.

new Thread((Runnable) null) selects this overload but provides no task: the default run() does nothing. Bare new Thread(null) is ambiguous because of Thread(String). If a security manager is configured in Java SE 21, it can deny thread creation, resulting in SecurityException.

Examples

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread caller = Thread.currentThread();
        Runnable task = () -> System.out.println(
                "caller thread: " + (Thread.currentThread() == caller));
        Thread worker = new Thread(task);

        System.out.println("constructed");
        worker.run();
        worker.start();
        worker.join();
        System.out.println("finished");
    }
}

Result

constructed
caller thread: true
caller thread: false
finished

The lambda captures the effectively final variable `caller`. The direct `run()` call prints `true`; execution after `start()` prints `false`. `join()` ensures that `finished` appears last.

Related lessons

  • Java · Lesson 49 · Intermediate · Version: 2
  • Java · Lesson 52 · Intermediate · Version: 2
  • Java · Lesson 53 · Intermediate · Version: 2
  • Java · Lesson 58 · Intermediate · Version: 2

Sources