当没有引用的新Thread()会被垃圾回收 [英] When wil the new Thread() without reference be garbage collected

查看:407
本文介绍了当没有引用的新Thread()会被垃圾回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the below example, new Thread() doesnt have any reference. Is it possible that it be garbage collected below it is dead ? Also without extending Thread class or implementing runnable, how are we creating a 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();
    }
}

推荐答案

一个尚未启动的新线程将以正常方式无法访问时将被垃圾回收.

A new thread that has not been started will be garbage collected when it becomes unreachable in the normal way.

已启动的新线程成为垃圾回收根".完成之前(之后),不会进行垃圾收集.

A new thread that has been started becomes a garbage collection "root". It won't be garbage collected until (after) it finishes.

在下面的示例中,new Thread()没有任何引用.可能是被废弃的垃圾收集了吗?

In the below example, new Thread() doesnt have any reference. Is it possible that it be garbage collected below it is dead ?

不.它已经启动,因此在完成/死亡之前将不会被垃圾收集.并且它确实具有可访问的引用,直到(至少)直到start()调用返回的点为止.

No. It has been started, and hence won't be garbage collected until it finishes / dies. And it does have a reachable reference until (at least) the point at which the start() call returns.

在不扩展Thread类或实现可运行的情况下,我们如何创建线程?

Also without extending Thread class or implementing runnable, how are we creating a thread?

在您的示例中,您已经创建了Thread的匿名子类;即扩展Thread的类.

In your example, you have created anonymous subclass of Thread; i.e. a class that extends Thread.

这篇关于当没有引用的新Thread()会被垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆