Card 02/ 08
All 8 cards
ExampleDifficulty: Intermediate1 min
Two Threads Printing at Once, and Output That Interleaves
Two threads, each printing five lines. Nothing is shared and nothing can go wrong, and the output is different from one run to the next.
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();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 5Each thread's own lines are 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 threads genuinely interleaved, with B handing over after four lines and finishing last.
The program is correct. Nothing here is a bug — and note how rarely the interleaving actually showed: six of those eight runs came out as one thread's block followed by the other's. A test that asserts on the exact output is testing the scheduler, and it will pass far more often than it should.