gpt4 book ai didi

java - 有人可以举例说明此处描述的有关线程安全变量的情况吗?

转载 作者:行者123 更新时间:2023-11-30 08:55:37 26 4
gpt4 key购买 nike

我正在学习 Java 多线程并遇到了 very good tutorial online .但是我不确定我是否理解作者解释线程安全对象、变量等的部分。引用他的话,

public void someMethod(){

LocalObject localObject = new LocalObject();

localObject.callMethod();
method2(localObject);
}

public void method2(LocalObject localObject){
localObject.setValue("value");
}

...the whole method someMethod() is thread safe. Even if the LocalObject instance is passed as parameter to other methods in the same class, or in other classes, the use of it is thread safe. The only exception is of course, if one of the methods called with the LocalObject as parameter, stores the LocalObject instance in a way that allows access to it from other threads.

我理解为什么 LocalObject 实例是线程安全的。但我想看一个异常(exception)情况的例子(上面 block 引用的最后一行)。如果有人可以编写适合最后一行所写内容的代码片段,那将非常有帮助。谢谢!

最佳答案

public class SomeClass {
private LocalObject cachedLocalObject;

public void someMethod() {
LocalObject localObject = new LocalObject();
localObject.callMethod();
method2(localObject);
}

public void method2(LocalObject localObject) {
this.cachedLocalObject = localObject;
localObject.setValue("value");
}

public LocalObject getCachedLocalObject() { return cachedLocalObject; }
}

method2() 中缓存对象然后在 getCachedLocalObject() 中将其公开以供外部使用的组合破坏了线程安全:一些其他线程可以使用 getCachedLocalObject () 获取和修改cachedLocalObject

关于java - 有人可以举例说明此处描述的有关线程安全变量的情况吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28923198/

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