Allowing an Application with Live Threads to Exit
An application will automatically exit when there are no
non-daemon threads running. In other words, a live daemon thread
does not prevent an application from exiting.
A thread must be marked as a daemon thread before it is
started. It cannot become a daemon thread after it is started. This
means that you could not implement, for example, a thread pool where
the threads become daemon threads only when inactive.
// This class extends Thread
class MyThread extends Thread {
MyThread() {
// Thread can be set as a daemon thread in the constructor
setDaemon(true);
}
// This method is called when the thread runs
public void run() {
// Determine if this thread is a daemon thread
boolean isDaemon = isDaemon();
}
}
// Create the thread
Thread thread = new MyThread();
// Thread can be set as daemon by the creator
thread.setDaemon(true);
// Start the thread
thread.start();
Post a comment