java 引用被回收_java - 没有引用的新Thread()什么时候会被垃圾回收

在下面的示例中,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的类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值