什么案例需要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?
我的问题是,如果我不同步实例成员,我什么时候会不正确?
for example if my class is
例如,如果我的班级是
public class MyClass {
private int instanceVar = 0;
public setInstanceVar()
{
instanceVar++;
}
public getInstanceVar()
{
return instanceVar;
}
}
in what cases (of usage of the class MyClass
) would I need to have methods: public synchronized setInstanceVar()
and public synchronized getInstanceVar()
?
在什么情况下(使用类MyClass)我需要有方法:public synchronized setInstanceVar()和public synchronized getInstanceVar()?
Thanks in advance for your answers.
提前感谢您的回答。
6 个解决方案
#1
19
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.)
这取决于您是否希望您的类是线程安全的。大多数类不应该是线程安全的(为简单起见),在这种情况下,您不需要同步。如果您需要它是线程安全的,您应该同步访问或使变量volatile。 (它避免了其他线程获得“陈旧”数据。)
更多相关文章
- WebService之基于REST机制的实现实例(Java版)
- javafx 和netty 混合使用出现线程不一致问题,求大神指点
- FilenameFilter文件名过滤器使用实例
- Java web环境配置和Servlet实例HelloWorld
- Java多线程之Thread、Runnable、Callable及线程池
- 急求用jersey2.x+spring3.x 开发rest webservice Java代码实例
- Java,Socket&TCP编程 实现多线程端对端通信与文件传输
- java高并发测试实例(精确到几百纳秒)
- Java错误:线程“main”中的异常java.lang.ArrayIndexOutOfBoundsE