Java中的悬空线程 [英] Dangling Threads in Java

查看:81
本文介绍了Java中的悬空线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中悬空线程会发生什么?

What happens to dangling threads in Java?

就像我创建一个应用程序一样,它会产生多个线程.并且其中一个线程没有完成,并且主程序在此之前完成了.这个悬空的线程会发生什么?它会无限期地留在线程池中,还是在阈值时间段后JVM杀死线程??

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???

推荐答案

这取决于线程是否已标记为守护程序". JVM退出时,守护进程线程将被杀死.如果有任何不是守护程序的线程,那么JVM将完全退出.它将等待这些线程先完成.

It depends on if the thread has been marked as "daemon" or not. Daemon threads will be killed when the JVM exits. If there are any threads that are not daemon then the JVM will not exit at all. It will wait for those threads to finish first.

默认情况下,线程采用其父线程的守护程序状态.主线程的守护进程设置为false,因此它所派生的所有线程也将为false.您可以将守护程序标志设置为true 之前,线程以此开始:

By default, threads take the daemon status of their parent thread. The main thread has daemon set false so any threads forked by it will also be false. You can set the daemon flag to true before the thread starts with this:

Thread thread = new Thread(...);
thread.setDaemon(true);
thread.start();

这篇关于Java中的悬空线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆