简体   繁体   English

在同步块中访问静态变量

[英]Access static variable in synchronized block

(Java synchronization problem)As my title, can I access a static variable in a synchronized block? (Java同步问题)作为标题,我可以在同步块中访问静态变量吗? Will it cause inconsistency ? 会引起不一致吗? Can anyone tell me the detail of the disadvantages or advantages of accessing a static variable synchronized block. 谁能告诉我访问静态变量同步块的缺点或优点的详细信息。

can I access a static variable in a synchronized block ? 如何在同步块中访问静态变量?

Yes, You can. 是的你可以。

Will it cause inconsistency ? 会引起不一致吗?

Static means shared across all the instances of that Class in a JVM. 静态意味着在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. 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++; } } } 
  2. Synchronized Static method. 同步静态方法。

     public class SomeClass { private static int sum = 0; public static synchronized void increaseSum() { sum++; } } 
  3. Synchronize on class object 在类对象上同步

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM