在下面的例子中,new Thread() 没有任何引用。它是否有可能在它死了下面被垃圾收集? 同样,在不扩展 Thread 类或实现 runnable 的情况下,我们如何创建线程?
public class TestFive {
private int x;
public void foo() {
int current = x;
x = current + 1;
}
public void go() {
for(int i = 0; i < 5; i++) {
new Thread() {
public void run() {
foo();
System.out.print(x + ", ");
}
}.start();
}
}
public static void main(String args[]){
TestFive bb = new TestFive();
bb.go();
}
}
最佳答案
未启动的新线程在正常情况下无法访问时将被垃圾回收。
已启动的新线程成为垃圾收集“根”。在它完成之前(之后)它不会被垃圾收集。
In the below example, new Thread() doesnt have any reference. Is it possible that it be garbage collected below it is dead ?
没有。它已经启动,因此在它完成/死亡之前不会被垃圾收集。在(至少)start()
调用返回之前,它确实有一个可达的引用。
Also without extending Thread class or implementing runnable, how are we creating a thread?
在您的示例中,您已经创建了Thread
的匿名子类;即扩展 Thread
的类。
关于java - 没有引用的 new Thread() 什么时候会被垃圾回收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6409262/