gpt4 book ai didi

java - 这段 Java 代码什么时候会发生垃圾回收?

转载 作者:太空宇宙 更新时间:2023-11-04 06:56:06 24 4
gpt4 key购买 nike

在我的示例代码中,我的哪些 Test 对象将有资格在执行结束时进行垃圾回收?

interface Animal1
{
void makeNoise();
}


class Horse implements Animal1
{
Long weight = 1200L;

@Override
public void makeNoise()
{
System.out.println("Whinny");
}
}

public class Test extends Horse
{
public void makeNoise()
{
System.out.println("wginny");
}

public static void main(String str[])
{
Test t1 = new Test();
Test t2 = new Test();
Test t3 = new Test();
t3 = t1;
t1 = t2;
t2 = null;
t3 = t1;
}
}

最佳答案

    Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
t3=t1;
t1=t2;
t2=null;
t3=t1;

答案是 t3 和 t1。t2 仍然有一个存储到 t1 中的引用,然后存储到 t3 中。为 t1 和 t3 创建的原始对象符合垃圾回收条件,因为它们不再具有强引用,因为它们保存了不同的值。一个很好的心理锻炼,但这可能是你只是复制粘贴的家庭作业。

一旦对其封闭对象的强引用消失,长整型都可以进行垃圾回收。

或者,如果您的应用程序退出,所有对象都有资格进行垃圾回收。

关于java - 这段 Java 代码什么时候会发生垃圾回收?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22721026/

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