What will happen when a Java thread is set to null

2019-01-18 02:23发布

After a thread started, if the reference of the thread is set to null, what will happen to the thread? Does it stop? Is it eligible for GC?

Like this:

t.start();
t = null;

4条回答
干净又极端
2楼-- · 2019-01-18 02:43

The thread will be running, its reference is just set to null and thats why it will not be eligible for GC.

查看更多
Fickle 薄情
3楼-- · 2019-01-18 02:50

No, setting the reference to null will not effect the thread, other than it has one less reference pointing at it. And yes, any object with active references pointing at it will not be garbage collected. If you want the thread to be eligible for GC (and more importantly stop doing stuff) then interrupt what it is doing:

someThread.interrupt();

from the Oracle docs:

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate

查看更多
相关推荐>>
4楼-- · 2019-01-18 02:51

Live thread will continue running even its reference is set to null.
Just like any other object, when there are no references to it, it is eligible to GC. The tricky point is that a running thread has a reference in a ThreadGroup even if your program does not retain one, thus a running thread is never GCed.

查看更多
三岁会撩人
5楼-- · 2019-01-18 02:58

what will happen to the thread?

Nothing.

Does it stop?

No.

Is it eligible for GC?

No.

查看更多
登录 后发表回答