Discussion Locked

using setDaemon

0 helpful
5 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I have a class implementing Runnable with
main() creating and starting one (1) thread.
I would like to quit the program, exiting
main(), and have my one (1) thread continue running indefinitely. I tried commenting
out // adjThread.setDaemon(true) with no
success, when I quit the program, the
adjThread still seems to die with main().
I also tried adjThread.setDaemon(false)
with no luck. Any advice on this would
be greatly appreciated.

5 replies

by kris.verbeeck

If you explicitly call the System.exit() method, then you kill the VM and that results in all threads terminating. If you want to keep the thread running, then don't call exit().

Example:
public class Test {
public static void main (String args[ ])
{
Thread t = new Thread() {
public void run() {
while (true) {
try {
sleep(1000);
} catch (Exception e) {}
}
}
};
t.start();
// Program stops here automatically
}
}

The thread in this program will run forever, but the actual main program does not have anything to execute anymore after the t.start() line, i.e. the program is finished.

If you start this in a shell (unix shell or dos box on windows), then you will not get your command prompt back, because the VM is still running that one thread.

This discussion is closed to new replies.