Card 07/ 08
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.
// 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 and a stack trace for IllegalThreadStateException, in either order | Yes, 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.
← → move through sections and cards