Java中静态变量的线程安全 [英] Thread safety for static variables in java

查看:1234
本文介绍了Java中静态变量的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My question is related to thread safety of static variables.

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

}

如果两个线程(具有静态锁定的t1和具有对象锁定的t2)可以 同时进行,那么如何对A类进行状态测试 线程安全吗?

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?

可能是,我缺少一些非常基本的内容,但不确定其工作原理.

May be , I am missing something very basic, but not sure how it works.

根据以下答案,我得到的印象是,如果这些状态具有 为了使线程安全,则两个锁都应由一个 正在更新此状态或确保正在访问它的线程 仅通过静态方法或仅通过非静态方法.对吧?

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?

推荐答案

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

This is not thread safe. The methods use different monitor objects: the static method uses the class, and the instance method synchronizes using the object instance. You can make the instance method use the class as the monitor object by:

synchronized (A.class) {
...

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

if you need to. I'd consider making both methods static though, unless you need to access instance variables.

这篇关于Java中静态变量的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆