Java SE API
Thread.join(Duration)
Wait up to the supplied duration for a started thread to terminate; return whether terminated.
Formal Syntax & Structure
java syntaxjava
boolean join(Duration duration) throws InterruptedExceptionParameters & Attributes
| Name | Type | Description |
|---|---|---|
| duration | Duration | Maximum wait duration |
Working Example
Example Snippetjava
import java.time.Duration;import java.util.concurrent.*;public class Main { // Only finite tasks and timed coordination are used in these examples. static void finish(Thread thread) throws InterruptedException { try { if (!thread.join(Duration.ofSeconds(3))) { thread.interrupt(); if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop"); throw new AssertionError("worker timed out"); } } catch (InterruptedException e) { thread.interrupt(); throw e; } } public static void main(String[] args) throws Exception { Runnable work = () -> System.out.println(Thread.currentThread().getName()); Thread worker = new Thread(work, "catalog-worker"); worker.run(); System.out.println(worker.getState()); worker.start(); finish(worker); System.out.println(worker.getState()); }}