Thread initialized to null in java

public class ThreadState {

    public static void main(String[] args){
            Thread t = new Thread(){
            public void run(){
                       // infinite loop
                       while (true) {
                        try {

                         Thread.sleep(1000);
                        }
                        catch (InterruptedException e) {
                        }

                        System.out.println("thread is running..."+Thread.currentThread().toString());
                       }

            }
        };
        t.start() ; 
        t = null ;
        while (true) {
              try {

              Thread.sleep(3000);
              }
              catch (InterruptedException e) {
              }
              System.out.println("thread is running..."+Thread.currentThread().toString());
        }   

    }
}

The instance instance t is initialized to zero. yet he is able to run and print his details on the console. You need an explanation of this

+3
source share
6 answers

Instance topic t is initialized to zero

No, the variable is Threadset to null. Variables are not instances - it is worth making absolutely sure that you understand this.

Changing the value of a variable does not affect an existing object Threadat all.

+10
source

t = null;just removes the link to the instance Thread.
This does not affect the stream itself.

In particular, an executable instance Threadwill never be GC'd.

+5

t null, , null , .

, :

,

Object t = new Thread() {...}
t.start
Thread t2= (Thread)t;
t="Orange";

, ? , t t2?

t , - t, , null .

Integer a = 2;
a=null;
+1

@JonSkeet , t = null Thread, t. , JVM , , , GC'd.

, :

System.out.println("thread is running..."+Thread.currentThread().toString());

, , - , . " ", main(). , , , , JVM . , , , JVM, .

+1

t null , . , .

. while (true) , , . Daemon , - , - , , , .

, . , InterruptedException , .

0

, , .. " Thread ".

, , -

In a programming method that uses static or global memory locally for a stream. Since usually all threads in a process have the same address space, which is sometimes undesirable. In other words, data in a static or global variable is usually always in the same memory cell when threads from the same process refer to it. Each thread has its own stack.

Hope this conceptual explanation is helpful.

0
source

All Articles