我的问题与静态变量的线程安全有关。
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/