start and join
- Java course
- Advanced
- Lesson 57/82
- 5 min
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.
Practice 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").
Starter code
// Define Worker extending Thread
// Call println in run()
// Write main in JoinDemo; call start and join, then print Main doneSample 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");
}
}Expected output
Worker done Main done
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match start/join concepts
| Term | Meaning |
|---|---|
start() |
Launches a new thread |
join() |
Waits until done |
run() |
Direct call |
Thread.State |
Gives the state |
2 Complete the join call
Thread t = new HelloThread();
t.start();
t.____();
System.out.println("Bitti");
Thread t = new HelloThread();
t.start();
t.join();
System.out.println("Bitti");
Explanation: join() waits for the thread to finish.
3 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 Correct answer
- An error is thrown
- Nothing happens
Explanation: Calling run() directly runs as a normal method; no new thread starts.