Propagating “daemon”-status to all child-threads in Java

旧巷老猫 提交于 2019-12-13 15:16:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!