Java
start and join
Learn thread management with start and join.
start and join
start() launches a new thread; join() blocks the caller until that thread finishes. This is essential for ordered output.
Thread t = new HelloThread();
t.start();
t.join();
System.out.println("Done");
Without join(), the main flow may continue before the thread finishes, scrambling the order. join can also take a duration: join(1000) waits at most one second. This control guarantees specific output sequences.
join and InterruptedException
The join() call can throw InterruptedException. A waiting thread can be interrupted by another via interrupt().
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Re-setting the interrupted status after catching is good practice. This lets upper layers notice the interrupt request. This is the standard way to stop threads cooperatively.
Exercise Ordered output with start and join
Define a Worker class that extends Thread; its @Override run() body calls System.out.println("Worker done"). In a JoinDemo class write main; create a Worker instance, call start(), wait with join() (wrap in try/catch or declare throws), and finally print System.out.println("Main done").
Show example solution
class Worker extends Thread {
@Override
public void run() {
System.out.println("Worker done");
}
}
class JoinDemo {
public static void main(String[] args) throws InterruptedException {
Worker w = new Worker();
w.start();
w.join();
System.out.println("Main done");
}
}
Test yourself
-
Match start/join concepts
- start()
- Launches a new thread
- join()
- Waits until done
- run()
- Direct call
- Thread.State
- Gives the state
-
Complete the join call
Thread t = new HelloThread();
t.start();
t.____();
System.out.println("Bitti");
Show answer
Thread t = new HelloThread();
t.start();
t.join();
System.out.println("Bitti");
-
What happens if you call a Thread's run() method directly?
- A new thread starts
- Runs as a normal method in the caller's flow
- An error is thrown
- Nothing happens
Show answer
Runs as a normal method in the caller's flow — Calling run() directly runs as a normal method; no new thread starts.
Next lesson: synchronized