Java多线程两个线程实例是相同的线程对象

时间:2012-11-15 06:33:29

标签: java multithreading

我对this代码中的代码段感到困惑:

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)的目的是什么?

2 个答案:

答案 0 :(得分:3)

  

这是否意味着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已完成,因此您在NPE内未获得if-construct,您试图中断该引用指向的线程。因此,如果该引用指向null,那么您没有与该中断引用相关联的任何线程。

答案 1 :(得分:0)

  

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

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

Thread testThread = m_logTestThread;

此行表示testThread将开始指向m_logTestThread所指向的同一对象。即两者都指向T.

m_logTestThread = null;

此行表示m_logTestThread将开始指向null,即它不再指向T.但是,它不会更改testThread,而testThread仍然是指着T。

  

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

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

相关问题