gpt4 book ai didi

Java 线程和垃圾收集

转载 作者:行者123 更新时间:2023-12-02 05:31:54 25 4
gpt4 key购买 nike

我在无数地方读到,正在运行的线程是垃圾收集根(即它们驻留在堆栈上,GC 识别它们并跟踪它们以确定它们内部的对象是否仍然可访问)。此外,GC 根本身永远不会被垃圾回收。

我的困惑在于:如果在线程停止之前从线程内分配的对象永远无法被垃圾收集,那么在唯一线程是主线程的单线程程序中如何进行垃圾收集?

显然我在这里遗漏了一些东西。

最佳答案

首先,线程(堆栈)在其存活时只是一个 GC 根。当线程终止时,它不再是GC根。

My confusion is here: If the objects allocated from within a thread can never be garbage collected until the thread is stopped, how then is anything garbage collected in single-threaded programs where the only thread is the main thread ?

你的前提是不正确的。

哪个线程分配对象并不重要。重要的是线程分配的对象是否仍然可访问。如果它变得无法访问(例如,如果您没有将对象的引用放入局部变量中)...那么它可以被收集。

关于Java 线程和垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25450326/

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