Why thread output changes every run
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)The same multithreaded program can print its lines in a different order every time you run it. The order is decided by the thread scheduler, not by your code, so you learn to reason about which orders are possible.
The thread scheduler decides who runs
The thread scheduler is the part of the operating system that decides which thread runs on which CPU core, and for how long. Java threads are scheduled by it, and your code does not control the exact order.
Example 1 · Two threads, a different order each run
public class SchedulerDemo { static void work(String name) { for (int i = 1; i <= 4; i++) { System.out.println(name + i); try { Thread.sleep(1); // a tiny pause, like waiting for the network } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
public static void main(String[] args) throws InterruptedException { Thread a = new Thread(() -> work("A"), "thread-A"); Thread b = new Thread(() -> work("B"), "thread-B"); a.start(); b.start(); a.join(); b.join(); System.out.println("done"); }}A1 B1 B2 A2 A3 B3 B4 A4 done
What this code does
- The A and B lines are mixed, and the mix changes from run to run: the scheduler decides which thread runs after each pause. Run it a few times to see it.
- Some things never change:
A1toA4stay in order,B1toB4stay in order, anddoneis always last becausemainprints it after bothjoin()calls.
A thread runs for a short time slice, often a few milliseconds, and may then be paused so another thread gets the core. A thread can also pause itself by waiting (for sleep, a file or the network). Which thread goes next depends on the number of cores, the other programs running, timing and luck. So the same program can print its lines in a different order on each run, on each computer and even under a debugger. That is normal behaviour, not a bug in Java.
Interleaving of print statements
Interleaving is the mixing of steps from different threads into one sequence. Each thread keeps its own order, but the steps of two threads are shuffled together, like two queues merging at one ticket window.
Example 2 · Lines broken by other threads' output
import java.io.ByteArrayOutputStream;import java.io.PrintStream;
public class MixedLinesDemo { static final int LINES = 20_000;
// Prints LINES lines per thread into a buffer and counts the lines that came out wrong. static int brokenLines(boolean onePrintPerLine) throws InterruptedException { PrintStream console = System.out; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); System.setOut(new PrintStream(buffer));
Runnable booking = () -> { String name = Thread.currentThread().getName(); for (int i = 0; i < LINES; i++) { if (onePrintPerLine) { System.out.println("seat booked by " + name); } else { System.out.print("seat booked "); System.out.print("by "); System.out.println(name); } } }; Thread a = new Thread(booking, "A"); Thread b = new Thread(booking, "B"); a.start(); b.start(); a.join(); b.join();
System.setOut(console); int broken = 0; for (String line : buffer.toString().split("\n")) { if (!line.trim().equals("seat booked by A") && !line.trim().equals("seat booked by B")) { broken++; } } return broken; }
public static void main(String[] args) throws InterruptedException { System.out.println("Three print calls per line: " + brokenLines(false) + " broken lines"); System.out.println("One println per line : " + brokenLines(true) + " broken lines"); }}Three print calls per line: 3058 broken lines One println per line : 0 broken lines
What this code does
- The program sends the output to a buffer (
System.setOut) and counts lines that are not exactlyseat booked by Aorseat booked by B. With threeprintcalls per line, the other thread often slips in between, so thousands of lines come out garbled. The number changes on every run, and on some runs the threads do not overlap at all and it is 0. - With one
printlnper line, each line is written in one piece, so the count is 0. The order of the A and B lines still varies; only the lines themselves stay whole.
A single println call normally prints its whole line in one piece: on the JDK, PrintStream locks itself while it writes. But a line built from several print calls can be cut in the middle by another thread's output. Build the whole line first, then print it once.
Reading "one possible output" in examples
From this lesson on, many examples are labelled Sample output. That label means "one real run": your run may show the same lines in a different order, or different numbers, and still be correct.
Example 3 · Fixed lines and moving lines
public class FixedAndMovingDemo { public static void main(String[] args) throws InterruptedException { System.out.println("main: Tatkal booking opens"); // always first
Thread counter1 = new Thread(() -> System.out.println("counter-1: ticket for Asha"), "counter-1"); Thread counter2 = new Thread(() -> System.out.println("counter-2: ticket for Ravi"), "counter-2"); counter1.start(); counter2.start(); System.out.println("main: waiting for counters"); // can move
counter1.join(); counter2.join(); System.out.println("main: 2 tickets booked"); // always last }}main: Tatkal booking opens main: waiting for counters counter-2: ticket for Ravi counter-1: ticket for Asha main: 2 tickets booked
What this code does
- The first line is printed before any
start(), so it is always first. The last line is printed after bothjoin()calls, so it is always last. - The three middle lines can come in any order:
mainruns on afterstart(), and the two counters race each other. This run shows one of the 6 possible orders.
Some lines are fixed even in a threaded program. Everything main prints before start() comes first, and everything it prints after join() comes last. Only the lines in between can move. Good programs put their final results after join(), so the important output never changes.
Listing which outputs are possible and which are not
To list the possible outputs of a small threaded program, keep each thread's own order and try every way of shuffling the threads' steps together. Thread A printing A1 A2 and thread B printing B1 B2 give 6 possible outputs.
Example 4 · Listing every possible output
import java.util.ArrayList;import java.util.List;
public class PossibleOutputsDemo { // Every way to merge two threads' steps, keeping each thread's own order. static void merge(List<String> a, int i, List<String> b, int j, String soFar, List<String> out) { if (i == a.size() && j == b.size()) { out.add(soFar.trim()); return; } if (i < a.size()) { merge(a, i + 1, b, j, soFar + " " + a.get(i), out); // thread A goes next } if (j < b.size()) { merge(a, i, b, j + 1, soFar + " " + b.get(j), out); // thread B goes next } }
public static void main(String[] args) { List<String> outputs = new ArrayList<>(); merge(List.of("A1", "A2"), 0, List.of("B1", "B2"), 0, "", outputs);
System.out.println(outputs.size() + " possible outputs:"); for (String o : outputs) { System.out.println(" " + o); } System.out.println("Is \"A2 A1 B1 B2\" possible? " + outputs.contains("A2 A1 B1 B2")); }}6 possible outputs: A1 A2 B1 B2 A1 B1 A2 B2 A1 B1 B2 A2 B1 A1 A2 B2 B1 A1 B2 A2 B1 B2 A1 A2 Is "A2 A1 B1 B2" possible? false
What this code does
- At every step either thread A or thread B can go next, as long as it has steps left. Trying both choices gives every legal interleaving: 6 for two steps each.
A2 A1 B1 B2is not in the list because it breaks thread A's own order. This program has a fixed output: it lists the possibilities instead of running threads.
- Each thread keeps its own order of statements.
- Nothing from a thread appears before its
start()call. - Everything a thread prints appears before the
join()on it returns.
An output is impossible if it breaks a thread's own order (A2 before A1), shows a line from a thread before the start() that created it, or shows a line of main after join() before a line of the joined thread.
Next step
Check your understanding
12 quick questions