如何在Java中运行不同类的实例的线程之间同步静态变量? [英] How to synchronize a static variable among threads running different instances of a class in java?

查看:227
本文介绍了如何在Java中运行不同类的实例的线程之间同步静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在一个方法使同步到该对象之前使用synchronize关键字。

也就是说,运行同一个对象实例的2个线程将被同步。

,由于同步是在对象级别,运行不同实例的对象的2个线程将不会同步。因此,如果我们在该方法调用的一个java类中有一个静态变量,我们希望它在类的实例之间同步。

这两个实例在两个不同的线程中运行。 br>
我们可以通过以下方式实现同​​步?

I know that using the synchronize keyword before a method brings synchronization to that object.
That is, 2 threads running the same instance of the object will be synchronized.
However, since the synchronization is at the object level, 2 threads running different instances of the object will not be synchronized. So, if we have a static variable in a java class that is called by the method, we would like it to be synchronized across instances of the class.
The two instances are running in 2 different threads.
Can we achieve synchronization in the following way?


public class Test  
{  
   private static int count = 0;  
   private static final Object lock= new Object();    
   public synchronized void foo() 
  {  
      synchronized(lock)
     {  
         count++;  
     }  
  }  
}

这是真的,因为我们已经定义了一个对象'这是静态的,我们正在使用关键字synchronized为那个锁,静态varibale计数现在同步跨类的实例。

Is it true that since we have defined an object 'lock' that is static and we are using the keyword synchronized for that lock, the static varibale count is now synchronized across instances of class Test?

推荐答案

有多种方法可以同步对静态变量的访问。

There are several ways to synchronize access to a static variable.


  1. 使用同步静态方法。这将同步类对象。

  1. Use a synchronized static method. This synchronizes on the class object.

public class Test {
    private static int count = 0;

    public static synchronized void incrementCount() {
        count++;
    }
} 


  • 在类对象上显式同步

  • Explicitly synchronize on the class object.

    public class Test {
        private static int count = 0;
    
        public void incrementCount() {
            synchronized (Test.class) {
                count++;
            }
        }
    } 
    


  • 其他静态对象。

  • Synchronize on some other static object.

    public class Test {
        private static int count = 0;
        private static final Object countLock = new Object();
    
        public void incrementCount() {
            synchronized (countLock) {
                count++;
            }
        }
    } 
    



  • b $ b

    在许多情况下,方法3是最好的,因为锁对象不会暴露在你的类之外。

    Method 3 is the best in many cases because the lock object is not exposed outside of your class.

    这篇关于如何在Java中运行不同类的实例的线程之间同步静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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