有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程线程在java中初始化为null

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());
        }   

    }
}

线程实例t被初始化为null。。它仍然能够在控制台上运行并打印其详细信息。需要解释一下吗


共 (5) 个答案

  1. # 1 楼答案

    Thread instance t is initialized to null

    否,Thread变量设置为空值。变量不是实例——值得确保您理解这一点

    更改变量的值根本不会影响现有的Thread对象

  2. # 2 楼答案

    我认为Jon是正确的,即“更改变量的值根本不会影响现有的线程对象。”

    但你需要的实际解释是

    In programming method that uses static or global memory local to a thread. Because normally all threads in a process share the same address space, which is sometimes undesirable. In other words, data in a static or global variable is normally always located at the same memory location, when referred to by threads from the same process. Each thread has its own stack.

    希望给出的概念解释有帮助

  3. # 3 楼答案

    @JonSkeet和其他人解释得很好,然后你设置t = null你根本没有改变正在运行的Thread,你只是在改变变量t。一旦线程启动,JVM就会管理线程,因此即使没有对它的引用,它也会运行,不会被GC调用

    另一件需要指出的事情是,在接下来的循环中,你正在做一个:

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

    这不是打印出你刚刚分叉的线程的状态,而是打印出当前的线程。这是运行main()方法的“主线程”。主线程可以完成,您分叉的线程将继续运行——防止JVM退出。只有当分叉的线程被标记为守护进程线程时,JVM才会在主线程完成时完成

  4. # 4 楼答案

    将t设置为null,这与线程本身无关,它只是将null分配给存储实例引用的变量

    也许这会有帮助:

    如果你这么做呢

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

    你会期待神奇的事情也会发生吗?如果将t传递给另一个方法,而不是在t2中存储另一个引用,会怎么样

    t只是线程引用的占位符,将某个内容分配给t对线程的影响与将null分配给a对数字2的影响一样大

    Integer a = 2;
    a=null;
    
  5. # 5 楼答案

    t = null;只是删除对Thread实例的引用
    它不会影响线程本身

    特别是,一个正在执行的Thread实例永远不会被GC'd