Card 07/ 08

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.

java
// 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
Each program, what it prints, and whether the process exits
PrintsExits?
1work then main done, both on the main threadYes
2main done, and then nothingNo — the non-daemon loop keeps it alive
3main doneYes — the daemon is killed where it stands
4work, then a stack traceYes, 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.