4

What happens to dangling threads in Java?

Like if I create an application and it spawns multiple threads. And one of the threads does not finish and the main program finishes before that. What will happen to this dangling thread? Will it stay in the thread pool infinitely or JVM will kill the thread after a threshold time period???

4

1 回答 1

9

这取决于线程是否被标记为“守护进程”。当 JVM 退出时,守护线程将被杀死。如果有任何线程不是守护进程,那么 JVM 根本不会退出。它将等待这些线程首先完成。

默认情况下,线程采用其父线程的守护进程状态。主线程设置了守护程序false,因此由它分叉的任何线程也将是false. 您可以在线程开始true 之前将守护程序标志设置为:

Thread thread = new Thread(...);
thread.setDaemon(true);
thread.start();
于 2012-04-05T12:59:49.763 回答