Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Thread — starting and coordinating threads

java.lang.Thread represents a thread of execution. Learn to create a thread with Runnable, launch it with start(), wait with join(), and use cooperative interruption without relying on timing delays.

Version: Java SE 21 (repository runtime); production runtime not attested

Syntax

new Thread(task);
new Thread(task, name);
thread.start();
thread.join();
thread.setName(name);
Thread.currentThread();
thread.interrupt();
Thread.sleep(millis);

java.lang.Thread represents a thread of execution. The Thread(Runnable) and Thread(Runnable,String) constructors create unstarted platform threads; the second assigns a name. Java SE 21 also supports virtual threads, but these constructors do not create them. Thread.setName changes the name, and Thread.currentThread() returns the currently executing thread.

Thread.start() schedules the task in a new thread; it can be called only once. Calling run() directly does not start a new thread. worker.join() makes the calling thread wait for worker to terminate. After successful return, the worker's writes are visible to the waiting thread.

Thread.sleep(long) pauses the current thread, not a referenced object. Timing depends on clocks and scheduling; it neither releases monitors nor provides synchronization. Do not substitute it for join() or coordination mechanisms.

Thread.interrupt() is a cooperative signal, not forced termination. Interrupted sleep() or join() throws InterruptedException and clears the calling thread's interrupt status. Propagate the exception or, when you cannot propagate it and are ending the task, restore the status with Thread.currentThread().interrupt(); do not ignore the signal.

The example deliberately interrupts its own thread before sleep(), avoiding a timing race. join() makes result[0] visible; sharing an array alone does not guarantee this. The repository runtime is Java SE 21. The production runtime is not attested.

This entry covers java.lang.Thread, including the constructors and methods described above.

Examples

public class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        int[] result = {0};
        Runnable task = () -> {
            Thread.currentThread().interrupt();
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                result[0] = 42;
            }
        };

        Thread worker = new Thread(task, "pending");
        worker.setName("worker");
        worker.start();
        worker.join();
        System.out.println(worker.getName() + ": " + result[0]);
    }
}

Result

worker: 42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources