Card 02/ 08

ExampleDifficulty: Intermediate1 min

Thread Example: Two Threads Printing at Once

Nothing is shared and nothing is wrong, and the output still changes from one run to the next.

Two threads running at the same time can take turns in any order, and the order changes between runs. Two threads that each print five numbered lines show it without anything being shared between them.

java
Runnable counter = () -> {
    for (int i = 1; i <= 5; i++) {
        System.out.println(Thread.currentThread().getName() + " " + i);
    }
};

new Thread(counter, "A").start();
new Thread(counter, "B").start();

The same program, run eight times in a row; three of the runs:

text
run 1   B 1  B 2  B 3  B 4  B 5  A 1  A 2  A 3  A 4  A 5
run 3   A 1  A 2  A 3  A 4  A 5  B 1  B 2  B 3  B 4  B 5
run 6   B 1  B 2  B 3  B 4  A 1  A 2  A 3  A 4  A 5  B 5
three of eight consecutive runs of the same program, on a two-core machine

Each thread's own lines stay in order: A 1 always comes before A 2. Nothing else is fixed. Which thread prints first changes between runs, and on run 6 the two really did interleave, with B pausing after four lines and finishing last.

The program is correct; nothing here is a bug. Notice how rarely the interleaving showed: six of the eight runs came out as one thread's block followed by the other's. A test that checks the exact output is testing the scheduler, and it will pass far more often than it should.