【问题标题】:Static Synchronized method provides Class level lock. What does Class Level Lock means?静态同步方法提供类级锁。等级锁定是什么意思?
【发布时间】:2014-09-03 11:01:50
【问题描述】:

这是否意味着任何线程,无论它获得的对象如何,都不会干扰其他线程在同步静态方法中执行。即使我们用 class_name.static_Method 调用。

Ex- If we have two thread :

public class Test implements Runnable {

  public synchronized static testMethod(){}

  public void run(){ testMethod(); }

  public static void main(String[] args) {
   Test obj1=new Test();
   Test obj2=new Test();
   Thread t1=new Thread(obj1);
   Thread t2=new Thread(obj2);
   t1.start(); // thread on object obj1
   t2.start(); // Thread on object obj2
   Test.testMethod(); // main thread
}
}

如果线程 t1 进入静态方法,那么 t2 和主线程将不会进入该方法,即使它们有不同的对象。 如果我错了,请纠正我。

【问题讨论】:

    标签: java multithreading static locking


    【解决方案1】:

    你在想这一切都是错的。不要这样写:

    public class Test implements Runnable {
        static synchronized SomeType testMethod() { ... }
        ...
    }
    

    改为写这个。它的意思完全一样,但它揭示了正在发生的事情:

    public class Test implements Runnable {
        static SomeType testMethod() { synchronized(Test.class) {...} }
        ...
    }
    

    然后,您只需要知道 Test.class 是一个唯一的对象(它是保存您的 Test 类的描述的对象),当然,没有两个线程可以同时在同一个对象上同步时间。

    同步实例方法也是如此:这个,

    public class Test implements Runnable {
        synchronized SomeType testMethod() { ... }
        ...
    }
    

    意思是一样的

    public class Test implements Runnable {
        SomeType testMethod() { synchronized(this) {...} }
        ...
    }
    

    但第二个告诉你真正发生了什么。

    【讨论】:

      【解决方案2】:

      如果线程 t1 进入静态方法,那么 t2 和主线程将不会进入该方法,即使它们有不同的对象

      它是一个static 方法,它是该类的所有实例(对象)的类级别(通用)方法,因此,对象不会事情。如果它声明为synchronized,那么执行该方法的线程将获取类对象(Class<Test>对象)上的锁

      static synchronized 方法如下所示

      public static testMethod(){
         synchronized(Test.class) {
            //method body
         }
      }
      

      由于一个类被加载一次(除非您定义了自定义的类加载器并重新加载该类),因此将只有一个类对象,它充当互斥锁

      【讨论】:

      • 是否意味着如果线程 t1 进入静态同步块,那么 t1 将获得两个锁,一个用于对象 obj1,第二个用于类对象。
      • Class.class 是什么意思?我们可以用它来代替 Test.class 吗?
      • No.. 没有必要在对象上获取锁,在这种情况下,t1 只会在类对象上获取锁。由于每个类只有一个类对象,当t1在执行static synchronized方法时,将不允许其他线程执行(互斥)
      • 如果程序包含线程 t3=new Thread(obj1) 那么线程 t1 将获得两个锁,一个用于对象 obj1,第二个用于类对象。
      【解决方案3】:

      T1 和 T2 正在对象 Test.class 上同步。记住类是 java.lang.Class 类型的对象

      【讨论】:

      • Class.class 是什么意思?我们可以用它来代替 Test.class
      • Class.class 表示 java.lang.Class 类的对象。为什么要对其进行同步。
      • 我只是想知道,如果我用 Class.class 替换 Test.class 是否在逻辑上是正确的。
      猜你喜欢
      • 1970-01-01
      • 2021-09-03
      • 2014-09-13
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 2015-05-09
      相关资源
      最近更新 更多