Thread basics: common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most bugs in early threaded code come from a few habits: calling run(), reading results before join(), and hiding InterruptedException. Each has a short, reliable fix, and a small checklist catches them all.
Mistake 1: calling run() instead of start()
t.run() is an ordinary method call: the task runs on the calling thread and no new thread is created. The program still gives correct results, so the bug hides. It only shows up as slowness, because the tasks run one after another.
Example 1 · run() makes the counters work one by one
public class CinemaRunBugDemo { static String[] bookAll(boolean useStart) throws InterruptedException { String[] seats = {"A1", "A2", "A3"}; String[] log = new String[3]; Thread[] counters = new Thread[3]; for (int i = 0; i < 3; i++) { int idx = i; counters[i] = new Thread(() -> log[idx] = seats[idx] + "@" + Thread.currentThread().getName(), "counter-" + (i + 1)); if (useStart) { counters[i].start(); } else { counters[i].run(); // the bug } } if (useStart) { for (Thread c : counters) { c.join(); } } return log; }
public static void main(String[] args) throws InterruptedException { System.out.println("run(): " + String.join(", ", bookAll(false))); System.out.println("start(): " + String.join(", ", bookAll(true))); }}run(): A1@main, A2@main, A3@main start(): A1@counter-1, A2@counter-2, A3@counter-3
What this code does
- Both versions book all three seats, so a quick test passes. Only the thread names show that the
run()version usedmainfor everything. - With
start()each seat is booked on its own counter thread, andmainjoins them before readinglog.
The fix is t.start(). While testing, print Thread.currentThread().getName() inside the task once: if every line says main, someone called run().
Mistake 2: forgetting join before reading a result
start() returns at once, so a result read straight after it is usually still empty: 0, null or half-built. Adding a sleep "to give it time" only hides the bug until the computer is busy.
Example 2 · Reading the result too early
public class EarlyReadDemo { public static void main(String[] args) throws InterruptedException { int[] rooms = {0}; Thread counter = new Thread(() -> { try { Thread.sleep(100); // reading the hostel register takes time } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } rooms[0] = 148; }, "room-counter");
counter.start(); System.out.println("Without join: free rooms = " + rooms[0]); counter.join(); System.out.println("After join: free rooms = " + rooms[0]); }}Without join: free rooms = 0 After join: free rooms = 148
What this code does
- The first read happens right after
start(), while the counter is still working, so it shows the starting value 0. On some other timing it could even show 148, which is why this bug comes and goes. - After
join()the value is always 148: the counter has finished and its write is guaranteed to be visible tomain.
The fix is join() before reading. It waits exactly as long as needed and guarantees that main sees everything the worker wrote. For several workers: start all, then join all, then read.
Mistake 3: swallowing InterruptedException
When an interrupt wakes a thread from sleep, join or wait, the method throws InterruptedException and clears the interrupt flag. An empty catch therefore throws the stop request away, and a loop that checks isInterrupted() keeps running.
Example 3 · Swallowed versus restored interrupt
public class TrackerInterruptDemo { static boolean stopsWhenAsked(boolean restore) throws InterruptedException { int[] updates = {0}; Thread tracker = new Thread(() -> { while (!Thread.currentThread().isInterrupted() && updates[0] < 8) { updates[0]++; // send one delivery-location update try { Thread.sleep(30); } catch (InterruptedException e) { if (restore) { Thread.currentThread().interrupt(); } } } }, "delivery-tracker"); tracker.start(); Thread.sleep(70); tracker.interrupt(); // the order was delivered tracker.join(); return updates[0] < 8; }
public static void main(String[] args) throws InterruptedException { System.out.println("Empty catch: stopped when asked = " + stopsWhenAsked(false)); System.out.println("Restored: stopped when asked = " + stopsWhenAsked(true)); }}Empty catch: stopped when asked = false Restored: stopped when asked = true
What this code does
- The interrupt nearly always arrives during
sleep, which clears the flag. With the emptycatchthe tracker runs on to its limit of 8 updates, as if nobody had asked it to stop. - Restoring the flag lets the loop condition see the request, so the tracker stops after about 3 updates. Timing decides the exact moment, so this output is a sample.
The fix is one of two: declare throws InterruptedException and catch it once at the top of the task, or restore the flag with Thread.currentThread().interrupt() and stop the current work.
Putting it together: a checklist for every threaded task
Most thread bugs in this module come from skipping one of a few steps. Run through them for every program that starts threads.
Example 4 · A result server that does everything right
class ToppersTask implements Runnable { private final String branch; private final int[] marks; String result; Exception error;
ToppersTask(String branch, int[] marks) { this.branch = branch; this.marks = marks; }
@Override public void run() { try { if (marks.length == 0) { throw new IllegalStateException("no marks uploaded for " + branch); } int best = marks[0]; for (int m : marks) { best = Math.max(best, m); } Thread.sleep(20); result = branch + " topper: " + best; } catch (InterruptedException e) { Thread.currentThread().interrupt(); // keep the stop request } catch (RuntimeException e) { error = e; // record, do not hide } }}
public class ResultServerDemo { public static void main(String[] args) throws InterruptedException { ToppersTask[] tasks = { new ToppersTask("CSE", new int[] {91, 87, 95}), new ToppersTask("ECE", new int[] {}), new ToppersTask("MECH", new int[] {78, 84, 80}) }; Thread[] servers = new Thread[tasks.length]; for (int i = 0; i < tasks.length; i++) { servers[i] = new Thread(tasks[i], "server-" + (i + 1)); servers[i].start(); // start, not run } for (Thread s : servers) { s.join(); } for (ToppersTask t : tasks) { System.out.println(t.error == null ? t.result : "FAILED: " + t.error.getMessage()); } }}CSE topper: 95 FAILED: no marks uploaded for ECE MECH topper: 84
What this code does
- Every item of the checklist is here: named threads,
start(), start-all-then-join-all, the interrupt restored, and errors recorded instead of lost. - The
sleep(20)stands for the time publishing takes. The ECE task fails, butmainknows about it and reports it clearly next to the two good results. The output is the same on every run.
- Name every thread, and create a new
Threadfor each run; neverstart()one twice. - Start all workers first, then
join()all of them, then read the results. - Make long tasks stoppable: check
isInterrupted()and never swallowInterruptedException. - Catch errors inside each task and record them, or at least set an uncaught exception handler.
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
The hall-ticket printer below prints main instead of its own name. Fix it so it runs on its own thread and main waits for it.
public class HallTicket { public static void main(String[] args) throws InterruptedException { Thread printer = new Thread(() -> System.out.println(Thread.currentThread().getName() + ": printed hall ticket for roll 2214"), "ticket-printer"); printer.run(); System.out.println("main: done"); }}ticket-printer: printed hall ticket for roll 2214 main: done
Exercise 2· Easy
This program usually prints Free rooms: 0. Fix it so it always prints the right number.
public class FreeRooms { public static void main(String[] args) throws InterruptedException { boolean[] occupied = new boolean[60]; for (int i = 0; i < 23; i++) { occupied[i] = true; } int[] free = {0}; Thread counter = new Thread(() -> { try { Thread.sleep(50); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } for (boolean o : occupied) { if (!o) { free[0]++; } } }, "room-counter"); counter.start(); System.out.println("Free rooms: " + free[0]); }}Free rooms: 37
Exercise 3· Medium
The tracker thread ignores interrupt() and runs all 20 updates. Fix the catch so it stops soon after being interrupted. The program then prints the line shown.
public class FixTracker { public static void main(String[] args) throws InterruptedException { int[] updates = {0}; Thread tracker = new Thread(() -> { while (!Thread.currentThread().isInterrupted() && updates[0] < 20) { updates[0]++; try { Thread.sleep(25); } catch (InterruptedException e) { } } }, "tracker"); tracker.start(); Thread.sleep(80); tracker.interrupt(); tracker.join(); System.out.println("tracker stopped early: " + (updates[0] < 20)); }}tracker stopped early: true
Exercise 4· Medium
Count today's attendance for four sections at the same time. Each thread section-A … section-D counts the true values in its own boolean[] and stores the count in its slot of an int[]. Join all, then print each count and the total. Use the data in the solution's arrays: A has 3 present, B 4, C 2, D 5.
section-A: 3 present section-B: 4 present section-C: 2 present section-D: 5 present Total present: 14
Exercise 5· Medium
The code below tries to send the OTP again by starting the same thread a second time and crashes with IllegalThreadStateException. Fix it so the second send runs on a new thread otp-2, reusing the same task.
public class OtpResend { public static void main(String[] args) throws InterruptedException { int[] count = {0}; Runnable send = () -> { count[0]++; System.out.println(Thread.currentThread().getName() + " sent OTP " + count[0]); }; Thread first = new Thread(send, "otp-1"); first.start(); first.join();
first.start(); first.join(); }}otp-1 sent OTP 1 otp-2 sent OTP 2
Exercise 6· Medium
A worker's failure only appears on System.err and main never knows. Without changing the task itself, attach a handler that stores the message, so main prints the line shown after join().
public class UploadHandler { public static void main(String[] args) throws InterruptedException { Thread upload = new Thread(() -> { throw new IllegalStateException("portal closed"); }, "upload"); upload.start(); upload.join(); System.out.println("main: upload ok"); }}main: upload failed (portal closed)
Exercise 7· Hard
Three cinema counters book seats at the same time. Each counter gets its own list of seat numbers and books them into its own List<String>; a seat number above 120 is invalid and must throw IllegalArgumentException("no seat " + n) inside the booking method. Each counter catches that, records the error message, and keeps booking the rest. After joining all, print each counter's bookings and errors as shown.
counter-1 booked [S12, S13] errors [] counter-2 booked [S40, S41] errors [no seat 130] counter-3 booked [S7] errors [] Total booked: 5
Exercise 8· Hard
Search for roll number 7234 in an array of 10,000 roll numbers (rolls[i] = i + 1000) using 4 threads search-1 … search-4, each scanning one quarter. Each thread stores the index it found (or -1) in its slot and also stops early if it is interrupted (check isInterrupted() in the loop). Join all and print who found it.
search-1: -1 search-2: -1 search-3: 6234 search-4: -1 Found roll 7234 at index 6234 by search-3
Interview questions
Questions interviewers ask on this topic.
What's next
You finished the preview of Thread Basics
Java Programming has 26 sections, 252 modules and 1949 lessons. An account opens every lesson and saves your progress.
Finish up
Mark complete & continue
Next: Two threads, one variable