在下面的示例中,new Thread()没有任何引用。可能是被废弃的垃圾收集了吗?
同样,在不扩展Thread类或实现可运行的情况下,我们如何创建线程?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的类。