System.out.println("result is "
- calc.getResult());
} catch (InterruptedException e) {
System.out.println("No answer: interrupted");
}
}
// ... definition of doSomethingElse ...
}
First, a new thread type, CalcThread, is defined to calculate a result. We start a CalcThread, do
something else for a while, and then join that thread. When join returns, CalcThread.run is
guaranteed to have finished, and result will be set. If CalcThread is already finished when
doSomethingElse has completed, join returns immediately. When a thread dies, its Thread object
doesn't go away, so you can still access its state. You are not required to join a thread before it can terminate.
Two other forms of join take time-out values analogous to wait. Here are the three forms of join:
public final voidjoin(long millis)tHRows InterruptedException
Waits for this thread to finish or for the specified number of milliseconds to
elapse, whichever comes first. A time-out of zero milliseconds means to wait
forever. If the thread is interrupted while it is waiting you will get an
InterruptedException.
public final voidjoin(long millis, int nanos)tHRows
InterruptedException
Waits for this thread to finish, with more precise timing. Again, a total
time-out of zero nanoseconds means to wait forever. Nanoseconds are in the
range 0999,999.
public final voidjoin()throws InterruptedException
Equivalent to join(0).
Internally, join is defined in terms of isAlive and can be logically considered to act as if written as
while (isAlive())
wait();
with the understanding that the runtime system will invoke notifyAll when the thread actually terminates.
14.9. Ending Application Execution
Each application starts with one threadthe one that executes main. If your application creates no other
threads, the application will finish when main returns. But if you create other threads, what happens to them
when main returns?
There are two kinds of threads: user and daemon. The presence of a user thread keeps the application running,
whereas a daemon thread is expendable. When the last user thread is finished, any daemon threads are
terminated and the application is finished. This termination is like that of invoking destroyabrupt and with