0

Recently,I read "Java Network Programming",in section 5.5,part 5.5.2.6 ,it has the following code:

public TimeSlicer(long milliseconds, int priority) {

    this.timeslice = milliseconds;

    this.setPriority(priority);

    // If this is the last thread left, it should not
    // stop the VM from exiting

    this.setDaemon(true);

}

just not quite understand the comments,what is the relationship of a daemon thread with the VM exiting?Thank you in advance.

zionpi
  • 2,593
  • 27
  • 38

2 Answers2

2

The Java VM exits when there are no non-daemon threads left running. By marking a thread as a daemon thread using setDaemon(true), you are telling the VM that it is okay to exit even if this thread is still left running.

From the java.lang.Thread documentation:

Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Thank you,but if a VM exits,how does a daemon thread still works?I think the VM is the environment of which all threads work in.So the VM exiting means the damon thread is free from its management,does it all right? – zionpi Mar 01 '12 at 01:33
  • When the VM exits, all threads stop. Daemon threads only run while the VM is running. – Greg Hewgill Mar 01 '12 at 01:52
  • It's quite obviously that VM is a great mistery. – zionpi Mar 01 '12 at 02:27
0

If all that you main() does is to create a thread which has an infinite loop (e.g while (true) { try { sleep(1000); } catch (Exception e) {}` then

  • if the thread is not a daemon then your program will run for ever
  • if the thread is a daemon the program will exit, killing the daemon thread

Specifically, setting a thread as daemon does not make the process a daemon, the kind that runs in background. For that, see this answer I wrote some time back

Community
  • 1
  • 1
Miserable Variable
  • 28,432
  • 15
  • 72
  • 133