gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:09:40 25 4
gpt4 key购买 nike

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

最佳答案

Does that mean testThread and m_logTestThread are different instances but point to the same object in the memory, so they are the same thread?

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

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

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 引用 指向它或有 循环引用 之前,一个对象不符合垃圾收集条件。

查看此链接:- Circular Reference - wiki page了解什么是 Circular Reference

what the purpose is of "if (testThread != null)" ?

很简单。从条件可以推断,它正在检查testThread 引用是否指向一个null 对象。null check 已完成,这样您就不会在 if-construct 中得到 NPE,您将在其中尝试中断线程该引用文献所指向的。因此,如果该引用指向 null,则您没有任何线程与该中断引用相关联。

关于Java多线程 线程的两个实例是同一个线程对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13392583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com