什么案例需要Java中的同步方法访问? [英] What Cases Require Synchronized Method Access in 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;
}
}
c $ c> MyClass )我需要有方法:
public synchronized setInstanceVar()
public synchronized getInstanceVar()
?
in what cases (of usage of the class MyClass
) would I need to have methods:
public synchronized setInstanceVar()
and
public synchronized getInstanceVar()
?
预先感谢您的答案。
推荐答案
这取决于你是否希望你的类是线程安全的。大多数类不应该是线程安全的(为了简单),在这种情况下,您不需要同步。如果你需要它是线程安全的,你应该同步访问或使变量volatile。 (避免其他线程获得过时数据。)
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中的同步方法访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!