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。 (它避免了其他线程获得“陈旧”数据。)

更多相关文章

  1. WebService之基于REST机制的实现实例(Java版)
  2. javafx 和netty 混合使用出现线程不一致问题,求大神指点
  3. FilenameFilter文件名过滤器使用实例
  4. Java web环境配置和Servlet实例HelloWorld
  5. Java多线程之Thread、Runnable、Callable及线程池
  6. 急求用jersey2.x+spring3.x 开发rest webservice Java代码实例
  7. Java,Socket&TCP编程 实现多线程端对端通信与文件传输
  8. java高并发测试实例(精确到几百纳秒)
  9. Java错误:线程“main”中的异常java.lang.ArrayIndexOutOfBoundsE

随机推荐

  1. Linux入门笔记之一:系统分区及挂载点
  2. ldconfig报错 :libstdc++.so.6.0.18-gdb.p
  3. linux下的C语言编程(总结篇)
  4. linux 的终端字体色和背景色的修改方法(三
  5. 操作系统的理念—以windows和linux为例
  6. ATT汇编与Intel汇编的区别,摘自《深入分析
  7. 使用Python获得鼠标增量!(在Linux中)
  8. Linux多线程总结
  9. linux 下命令行传参数问题
  10. Linux进程通信之匿名管道