gpt4 book ai didi

java - 为什么 Thread 实例的 isAlive() 方法给出错误的结果?

转载 作者:行者123 更新时间:2023-12-01 18:23:17 25 4
gpt4 key购买 nike

我开始知道下面的代码输出为 false ,但是当我们看到这个 Thread 实例时,我们创建的 thread 被设置为守护进程并且仍在运行,那么为什么方法调用 thread.isAlive() 会返回false ,给人错误的印象“线程已完成工作并且已死亡”

public class MyThreads {

private static class MyDaemonThread extends Thread {

public MyDaemonThread() {
setDaemon(true);
}

@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}

public static void main(String[] args) throws InterruptedException {
Thread thread = new MyDaemonThread();
thread.start();
thread.join();
System.out.println(thread.isAlive());
}
}

任何人都可以对此有想法吗?

最佳答案

thread.join(); 是一个表达式,告诉主线程等待 thread 终止。因此,只有当线程完成时,它才会转到打印语句。所以它是正确的结果,因为线程已经终止。

如果删除join,您将看到结果为 true

关于java - 为什么 Thread 实例的 isAlive() 方法给出错误的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27041881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com