访问同步块中的静态变量 [英] Access static variable in synchronized block

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

问题描述

(Java同步问题)作为我的标题,我可以在同步块中访问静态变量吗?会导致不一致吗?谁能告诉我访问静态变量同步块的优缺点的详细信息.

(Java synchronization problem)As my title, can I access a static variable in a synchronized block? Will it cause inconsistency ? Can anyone tell me the detail of the disadvantages or advantages of accessing a static variable synchronized block.

推荐答案

我可以访问同步块中的静态变量吗?

是的,你可以.

会导致不一致吗?

静态意味着在 JVM 中该类的所有实例之间共享.共享资源不是线程安全的.因此静态变量不是线程安全的.因此,如果多个线程试图访问一个静态变量,可能会导致不一致.

Static means shared across all the instances of that Class in a JVM. Shared resources are not thread-safe.Hence Static variables are not thread safe.So, if multiple threads tries to access a static variable, it may result in inconsistency.

我所知道的同步访问静态变量的方法.

The ways, which I know of to synchronize access to a static variable.

  1. 同步静态对象.

  1. Synchronize on Static object.

   public class SomeClass{
      private static int sum = 0;
      private static final Object locker = new Object();

      public void increaseSum() {
           synchronized (locker) {
           sum++;
      }
    }
  }

  • 同步静态方法.

  • Synchronized Static method.

    public class SomeClass {
        private static int sum = 0;
    
       public static synchronized void increaseSum() {
         sum++;
     }
    }
    

  • 在类对象上同步

  • Synchronize on class object

     public class SomeClass {
        private static int sum= 0;
    
        public void increaseSum() {
           synchronized (SomeClass .class) {
           sum++;
         }
       }
     } 
    

  • 这篇关于访问同步块中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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