[英]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是不同的實例,但指向內存中的同一個對象,所以它們是同一個線程?
這是部分正確的。 實際上testThread
和m_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是不同的實例,但指向內存中的同一個對象,所以它們是同一個線程?
testThread
和m_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.