Codectionary / Developer documentation / Java

Thread Control: sleep, join, interrupt

Java provides several methods for coordinating and controlling thread execution. Thread.sleep() pauses the current thread for a specified duration. join() makes the calling thread wait until another thread finishes before continuing. interrupt() signals a thread that it should stop what it's doing, a cooperative mechanism the target thread must actively check for and respond to.

Syntax

thread.join();\nThread.sleep(milliseconds);

Examples

Thread.sleep()

Pausing execution for a specified duration.

public class SleepExample {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Starting...");
        Thread.sleep(1000);  // pause for 1000ms (1 second)
        System.out.println("One second later");
    }
}

join(): Waiting for a Thread to Finish

Making the main thread wait for a worker thread to complete before continuing.

Thread worker = new Thread(() -> {
    for (int i = 1; i <= 3; i++) {
        System.out.println("Working: " + i);
    }
});

worker.start();

try {
    worker.join();  // main thread waits here until worker finishes
} catch (InterruptedException e) {
    System.out.println("Interrupted while waiting");
}

System.out.println("Worker finished, continuing main thread");

interrupt(): Requesting a Thread Stop

A cooperative way to signal a thread to stop, which the thread must check for itself.

Thread task = new Thread(() -> {
    int count = 0;
    while (!Thread.currentThread().isInterrupted()) {
        count++;
        if (count % 100_000_000 == 0) {
            System.out.println("Still working...");
        }
    }
    System.out.println("Task stopped, saw the interrupt signal");
});

task.start();

try {
    Thread.sleep(50);  // let it run briefly
    task.interrupt();   // request it to stop
} catch (InterruptedException e) {
    e.printStackTrace();
}

Best practices

  • Always handle InterruptedException from sleep() and join() - either propagate it, or re-set the interrupt flag with Thread.currentThread().interrupt() if you catch and swallow it
  • Use join() when your program logic genuinely depends on a thread completing before proceeding, rather than guessing with an arbitrary sleep() delay
  • Check Thread.currentThread().isInterrupted() periodically inside long-running tasks so they can respond promptly to interrupt() requests
  • Remember interrupt() does not forcibly stop a thread - it only sets a flag that well-behaved code is expected to check and respect

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading