Java守护线程:if-else与while循环执行表现差异原因咨询
守护线程两种分支行为差异的原因分析
首先得明确Java守护线程的核心规则:当JVM中仅剩下守护线程时,JVM会立即终止,不会等待守护线程执行完所有代码。你遇到的两种情况差异,本质是main线程结束时机和守护线程代码执行速度的竞争问题。
为什么if-else分支会输出?
当调用d.start()后,守护线程开始启动,但main线程此时还在收尾阶段(哪怕main方法启动线程后就没代码了,线程退出也需要一点时间)。而if-else分支的逻辑非常简单:只是判断线程类型然后打印一行文字,这个操作耗时极短,大概率能在main线程完全退出、JVM触发终止前执行完毕,所以能看到"It is Daemon"的输出。
为什么while循环没有输出?
while循环要执行20次打印操作,相对耗时更长。main线程启动守护线程后会快速退出,此时JVM检测到只剩守护线程,会直接终止进程,根本不会等守护线程把循环跑完——甚至可能循环还没开始执行,JVM就已经终止了,所以看不到任何输出。
验证结论的小实验
如果在main方法里加一行睡眠代码,让main线程多等一会儿,给守护线程足够的执行时间:
public class Main { public static void main(String[] args) throws InterruptedException { MyThread d = new MyThread(); d.setDaemon(true); d.start(); Thread.sleep(100); // 让main线程等待100毫秒 } }
这时候你会发现while循环的20次打印都能正常输出,因为main线程没立即退出,JVM不会终止,守护线程有足够时间执行完循环。
你的测试代码:
class MyThread extends Thread{ public void run(){ // In case of while loop it is not printing anything /* int count = 1; while(count<=20){ System.out.println(count++); } */ //In this case it is printing "It is Daemon" WHY ??? if(Thread.currentThread().isDaemon()){ System.out.println("It is Daemon"); }else{ System.out.println("it is not Daemon"); } } } public class Main { public static void main(String[] args) throws InterruptedException { MyThread d = new MyThread(); d.setDaemon(true); d.start(); } }
内容的提问来源于stack exchange,提问作者Deepak kumar soni
相关产品推荐
相关产品推荐

