gpt4 book ai didi

java - 为什么线程对象在作用域后没有被销毁?

转载 作者:行者123 更新时间:2023-11-29 07:04:27 24 4
gpt4 key购买 nike

我认为对象只存在于它们被定义的范围内。但是在这个程序中,执行thtest方法后,线程的t1对象仍然存在,我可以在输出中看到“hi”和“bye”。

public class apples {
public static void main(String args[]){
int b =1;
navid n = new navid();
n.thtest();
while (b==1){ System.out.println("bye"); }
}
}

public class navid {
int a=1;
public void thtest (){
Runnable te = new Runnable() {
public void run(){
try{
while (a==1){ System.out.println("hi");}
}catch(Exception e){}
}
};
Thread t1 = new Thread (te);
t1.start();
}
}

最佳答案

I thought that objects only exist in the scope that they've been defined.

这是一个错误的假设。对象存在直到不再有对它们的引用(或者直到它被垃圾收集,这取决于您的观点)。您可以将对对象的引用存储在定义对象之外的其他位置,并让它们在您需要时一直存在。

线程有些特殊,JVM 会跟踪一个线程并且它会继续运行直到它的 run() 方法结束,即使您的代码不包含对 Thread 对象的引用也是如此。

关于java - 为什么线程对象在作用域后没有被销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21426888/

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