Card 07/ 08
All 8 cards
ExerciseDifficulty: Advanced1 min
Four Programs: Write Down Which Ones Finish
Four short programs. For each, decide whether the process exits, and what is printed. All four before the reveal.
// 1
Thread t = new Thread(() -> System.out.println("work"));
t.run();
System.out.println("main done");
// 2
Thread t = new Thread(() -> { while (true) { } });
t.start();
System.out.println("main done");
// 3
Thread t = new Thread(() -> { while (true) { } });
t.setDaemon(true);
t.start();
System.out.println("main done");
// 4
Thread t = new Thread(() -> System.out.println("work"));
t.start();
t.start();What each of the four does
| Prints | Exits? | |
|---|---|---|
| 1 | work then main done, both on the main thread | Yes |
| 2 | main done, and then nothing | No — the non-daemon loop keeps it alive |
| 3 | main done | Yes — the daemon is killed where it stands |
| 4 | work, then a stack trace | Yes, with IllegalThreadStateException |
The first is the one to keep. run() gave the right output on the wrong thread, in the wrong order, and nothing complained — which is exactly why it is so hard to spot in a real program.
The fourth is the state machine showing through. A terminated thread cannot go back, so a Thread object is one job rather than a reusable worker.