Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

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

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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...