When wil new Thread () without a link will be garbage collected

In the example below, the new Thread () has no link. Is it possible that the garbage collected underneath is dead? Also, without an extension to the Thread class or a runnable implementation, how do we create 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();
    }
}
+5
source share
3 answers

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

The new thread that was started becomes the root garbage collection. This will not be garbage collection until (after) it ends.

In the example below, the new Thread () has no link. Is it possible that the garbage collected underneath is dead?

. , , , / . ( ) , start().

Thread runnable, ?

Thread; , Thread.

+10

, a Thread, , VM ( , ). , Thread, - , start() -ed, - , .

- Thread, , :

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

, , Runnable:

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

, , - , , - .

+3

, . for , for .

Thread, run()

+1

All Articles