gpt4 book ai didi

Java 多线程 - 本地对象引用是否共享?

转载 作者:行者123 更新时间:2023-11-30 07:02:42 25 4
gpt4 key购买 nike

我一直在阅读有关 Java 多线程的内容。我想到了一个关于跨线程资源共享的话题 here .这让我对本地对象引用有点困惑。

Local references to objects are a bit different. The reference itself is not shared. The object referenced however, is not stored in each threads's local stack. All objects are stored in the shared heap. If an object created locally never escapes the method it was created in, it is thread safe. In fact you can also pass it on to other methods and objects as long as none of these methods or objects make the passed object available to other threads.

前几行我能理解,但是作者对上面粗体行的意思是什么?更具体地说,他所说的本地转义是什么意思?

有人可以解释一下吗,可能用不同的例子。

最佳答案

在此测试中,HashSet 的使用是线程安全的,因为对它的唯一引用是在局部变量中,如果另一个线程进入此方法,它将创建一个新的 Set。

void x() {
Set s = new HashSet();
s.add(1);
}

但是如果我们在一个字段中保存对我们的 HashSet 的引用,那么另一个线程可能会同时更改它

Set s;

void x() {
s = new HashSet();
s.add(1);
}

void y() {
s.add(2);
}

关于Java 多线程 - 本地对象引用是否共享?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28892603/

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