Card 07/ 08

ExerciseDifficulty: Advanced1 min

Practice: Predicting Which Thread Programs Finish

run, start, a daemon and a second start: decide what each program prints and whether it exits.

Whether a Java process exits depends on its non-daemon threads (ordinary threads, which keep the process alive until they finish), and whether a new thread runs at all depends on start(). For each of the four programs below, write down what it prints and whether the process exits, all four before you open the answer.

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 and a stack trace for IllegalThreadStateException, in either orderYes, once the first thread finishes

The first is the one to remember. run() gave the right output on the wrong thread, and nothing complained, which is what makes it hard to spot in a real program.

The fourth shows the one-way states: a started thread cannot be started again, so the second start() throws. Its work line and the stack trace come from two threads at once, so across ten runs they appeared in both orders, and sometimes mixed together.