问题
If I have a Thread
object, I can call setDaemon(true)
on it to mark that this thread should not prevent application shutdown if all other non-daemon threads have terminated.
Is it possible to make this behavior automatically trickle down to all child-threads? I.e. if I have a thread that is marked as a daemon-thread, is there some way to enforce that all threads spawned by this thread are also automatically marked as daemon-threads?
回答1:
Is it possible to make this behavior automatically trickle down to all child-threads?
You don't need to do that since it is by default:
The newly created thread is initially marked as being a daemon thread if and only if the thread creating it is currently marked as a daemon thread. The method setDaemon may be used to change whether or not a thread is a daemon.
See this.
回答2:
You can use a ThreadGroup
, then set the ThreadGroup to daemon: myThreadGroup.setDaemon(true)
and then use this TreadGroup when you create a new Thread:
ThreadGroup myThreadGroup = new ThreadGroup(...);
myThreadGroup.setDaemon(true);
// ... and every time you create a thread:
Thread myThread = new Thread(myThreadGroup, "My #n Thread") { ... };
// ...
来源:https://stackoverflow.com/questions/17760951/propagating-daemon-status-to-all-child-threads-in-java