【问题标题】:Java Multi-Threading Two instances of threads are the same thread objectJava 多线程 两个线程实例是同一个线程对象
【发布时间】:2012-11-03 18:16:21
【问题描述】:

我对@9​​87654321@ 代码中的 sn-p 感到困惑:

void stopTestThread() {

    // thread should cooperatively shutdown on the next iteration, because field is now null
    Thread testThread = m_logTestThread;
    m_logTestThread = null;
    if (testThread != null) {
      testThread.interrupt();
      try {testThread.join();} catch (InterruptedException e) {}
    }
  }

是不是说 testThread 和 m_logTestThread 是不同的实例,但指向内存中的同一个对象,所以它们是同一个线程?

如果有,if (testThread != null) 的目的是什么?

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    这是否意味着 testThread 和 m_logTestThread 是不同的实例 但是指向内存中的同一个对象,所以它们是一样的 线程?

    这是部分正确的。实际上testThreadm_logTestThread 是两个不同的references 而不是instances。并且两个引用都指向同一个Thread 对象。因此,仅将 reference m_logTestThread 指向 null 不会使 testThread 引用也指向 null

    你也可以通过一个简单的例子在实践中看到它:-

    String str = "abc";
    String strCopy = str;  // strCopy now points to "abc"
    str = null;  // Nullify the `str` reference
    
    System.out.println(strCopy.length()); // Will print 3, as strCopy still points to "abc"
    

    因此,即使您将其中一个引用设置为 null,另一个引用仍然指向同一个 Thread 对象。一个对象在有0 reference 指向它或有circular reference 之前没有资格进行垃圾回收。

    查看此链接:-Circular Reference - wiki page 以了解 Circular Refeference 的确切含义。

    “if (testThread != null)”的目的是什么?

    很简单。您可以从条件推断,它正在检查testThread 引用是否指向null 对象。 null check 完成后,您不会在if-construct 中获得NPE,您试图中断该引用指向的线程。因此,如果该引用指向 null,那么您就没有与该引用关联的任何线程来中断。

    【讨论】:

    • An object is not eligible for Garbage Collection until it has 0 reference pointing to it. 不考虑循环引用
    【解决方案2】:

    是不是说 testThread 和 m_logTestThread 是不同的实例,但指向内存中的同一个对象,所以它们是同一个线程?

    testThreadm_logTestThread 是两个指向 Thread 对象的同一实例的引用。 (比如说T)

    Thread testThread = m_logTestThread;
    

    这一行意味着testThread 将开始指向m_logTestThread 指向的同一个对象。即两者都指向 T。

    m_logTestThread = null;
    

    这行意味着m_logTestThread 将开始指向null,即不再指向T。但是,它不会改变testThreadtestThread 仍然指向T。

    “if (testThread != null)”的目的是什么?

    因为testThread 可能OR 可能不是null,因此在使用testThread 之前使用此条件进行进一步计算。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 2011-03-07
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多