簡體   English   中英

Java多線程兩個線程實例是相同的線程對象

[英]Java Multi-Threading Two instances of threads are the same thread object

對此代碼中的代碼段感到困惑:

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

這是否意味着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 Refeference

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

這很簡單。 您可以從條件推斷出,它正在檢查testThread引用是否指向null對象。 完成null check ,以便在if-construct沒有得到NPE ,在那里你試圖中斷該引用所指向的Thread。 因此,如果該引用指向null ,那么您沒有與該中斷引用相關聯的任何線程。

這是否意味着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之前,此條件用於進一步計算。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM