CKTIS / Java
Thread: starting, joining, and interrupting
Create platform threads from Runnable tasks, start them once, read their results after joining, and handle cooperative cancellation without losing interrupt status.
Version: Java SE 21
Syntax
new Thread(task); // task: Runnable
new Thread(task, name); // name: String
worker.start(); // void
worker.join(); // void; throws InterruptedException
worker.join(millis); // long; same return and checked exception
worker.join(millis, nanos); // long, int; same return and checked exception
worker.join(duration); // java.time.Duration; boolean; throws InterruptedException
Thread.currentThread(); // static; returns Thread
worker.getName(); // returns String
worker.interrupt(); // request interruption of worker
Thread.currentThread().interrupt(); // set the calling thread's interrupt statusIn Java SE 21, both java.lang.Thread constructors create an unstarted platform thread, not a virtual thread. Thread(Runnable) generates a name; Thread(Runnable,String) uses the supplied name. Static Thread.currentThread() returns the thread executing the call. The instance method getName() returns that object's name, a label rather than a unique identifier.
worker.start() schedules the task to run on the new thread. Calling worker.run() directly runs the task on the calling thread. A second start() throws IllegalThreadStateException, even after termination. Actions before start() are visible to the started thread through the happens-before relation. Starting threads does not determine their execution order.
worker.join() makes the caller wait for a started worker to terminate; it returns immediately for an unstarted thread. After join() returns normally for a started worker, its writes are visible to the caller. Join every producer before reading its results: this neither fixes races among producers nor proves their tasks succeeded. The join(long) and join(long,int) overloads can return on timeout; all-zero arguments mean no timeout. join(Duration) reports whether the thread terminated and throws IllegalThreadStateException for an unstarted thread.
worker.interrupt() signals the worker; it does not forcibly stop it. When join() or await() throws InterruptedException, the calling thread's interrupt status is cleared. Propagate the exception when possible; otherwise clean up, restore the status with Thread.currentThread().interrupt(), and leave the cancellation path without reporting success. isInterrupted() reads status without clearing it; static Thread.interrupted() reads and clears the current thread's status. Do not rely on interrupting a thread that is not alive; in Java SE 21 a security manager can deny interruption of another thread.
Examples
import java.util.concurrent.CountDownLatch;
public class ThreadMethodsDemo {
public static void main(String[] args) throws InterruptedException {
var gate = new CountDownLatch(1);
var observations = new String[2];
Thread compute = new Thread(() -> observations[0] = "sum=" + (20 + 22));
Thread cancellable = new Thread(() -> {
Thread self = Thread.currentThread();
try {
gate.await();
} catch (InterruptedException e) {
self.interrupt();
observations[1] = self.getName() + ": cancelled; interrupted="
+ self.isInterrupted();
return;
}
}, "cancellable");
compute.start();
cancellable.start();
cancellable.interrupt();
compute.join();
cancellable.join();
System.out.println(observations[0]);
System.out.println(observations[1]);
}
}Result
sum=42 cancellable: cancelled; interrupted=true
The first thread records a sum; the named thread records cancellation. The latch stays closed, so await() responds to interruption whether it arrives before or during the wait. Only main prints, after both joins, so the line order does not depend on scheduling.
Related lessons
- Java · Lesson 25 · Advanced · Version: 2
- Java · Lesson 28 · Advanced · Version: 2
- Java · Lesson 30 · Advanced · Version: 2
- Java · Lesson 33 · Advanced · Version: 2
- Java · Lesson 34 · Advanced · Version: 2
- Java · Lesson 35 · Advanced · Version: 2
- Java · Lesson 36 · Advanced · Version: 2
- Java · Lesson 37 · Advanced · Version: 2
- Java · Lesson 38 · Advanced · Version: 2