When wil the new Thread() without reference be garbage collected

后端 未结 3 1372
耶瑟儿~
耶瑟儿~ 2020-12-19 06:45

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 implement

3条回答
  •  执笔经年
    2020-12-19 06:47

    No, a Thread which has been can't be garbage collected before the underlying VM thread (whether an OS-thread or not) has finished. I'm not sure offhand whether a Thread which doesn't have any obvious references to it but hasn't been start()-ed ends up causing a leak, or whether it can be collected - the latter, I'd expect.

    As for your second question - your code does extend Thread, using an anonymous inner class, here:

    new Thread() {
            public void run() {
                    foo();
                    System.out.print(x + ", ");
            } 
    }
    

    I would personally suggest that even if you did want to use an anonymous inner class here, it's generally neater to implement Runnable:

    new Thread(new Runnable() {
        public void run() {
            foo();
            System.out.print(x + ", ");
        } 
    })
    

    That way it's clear that you're just providing something to run, rather than trying to change any of the thread's core behaviour.

提交回复
热议问题