What Cases Require Synchronized Method Access in Java?(Java中哪些情况需要同步方法访问?)
问题描述
在什么情况下需要同步对实例成员的访问?我知道对类的静态成员的访问总是需要同步 - 因为它们在类的所有对象实例之间共享.
In what cases is it necessary to synchronize access to instance members? I understand that access to static members of a class always needs to be synchronized- because they are shared across all object instances of the class.
我的问题是,如果我不同步实例成员,我什么时候会出错?
My question is when would I be incorrect if I do not synchronize instance members?
例如,如果我的班级是
public class MyClass {
private int instanceVar = 0;
public setInstanceVar()
{
instanceVar++;
}
public getInstanceVar()
{
return instanceVar;
}
}
在什么情况下(使用类MyClass
)我需要有方法:public synchronized setInstanceVar()
和公共同步 getInstanceVar()
?
in what cases (of usage of the class MyClass
) would I need to have methods:
public synchronized setInstanceVar()
and
public synchronized getInstanceVar()
?
提前感谢您的回答.
推荐答案
这取决于你是否希望你的类是线程安全的.大多数类不应该是线程安全的(为简单起见),在这种情况下您不需要同步.如果您需要它是线程安全的,您应该同步访问或使变量可变.(它避免了其他线程获取陈旧"数据.)
It depends on whether you want your class to be thread-safe. Most classes shouldn't be thread-safe (for simplicity) in which case you don't need synchronization. If you need it to be thread-safe, you should synchronize access or make the variable volatile. (It avoids other threads getting "stale" data.)
这篇关于Java中哪些情况需要同步方法访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中哪些情况需要同步方法访问?


- 如何指定 CORS 的响应标头? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 获取数字的最后一位 2022-01-01