java - java中静态变量的线程安全

标签 java multithreading concurrency

我的问题与静态变量的线程安全有关。

Class A{
private static int test=0;
public static void synchronized  m1(){
    test=test+1;
}
public void synchronized  m2(){
   test=test+1;
}

}

If two threads, t1 having static lock and t2 having object lock, can continue simultaneously, then how will state test of class A will be thread safe?

可能是,我错过了一些非常基本的东西,但不确定它是如何工作的。

Based on below answers, I get the impression that if such states have to be made thread safe, then either both locks should be held by a thread which is updating this state, or make sure it is being accessed by either only static methods or only non-static methods. right?

最佳答案

这不是线程安全的。这些方法使用不同的监视对象:静态方法使用类,实例方法使用对象实例进行同步。您可以通过以下方式使实例方法使用该类作为监视对象:

synchronized (A.class) {
...

如果你需要的话。我会考虑将这两种方法设为静态,除非您需要访问实例变量。

关于java - java中静态变量的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27216098/

相关文章:

java - 在没有 eclipse 等的情况下调试 java 产品

multithreading - 没有TThread的情况下如何从线程过程访问类的成员?

python - 运行的 uwsgi 线程过多

java - 并发观察者模式

java - lock 是否锁定整个对象?

java - Eclipse 插件包卡在启动状态

java - 如何在包含 3 个 war 文件的 Eclipse 中调试应用程序?

java - 为一台计算机系统设置 Java 应用程序

java - 在多线程环境中清除嵌套循环中的 Map

sockets - 在 goroutines 中使用套接字的正确方法是什么