静态同步方法提供类级别锁定。 Class Level Lock意味着什么?

时间:2014-09-03 11:01:51

标签: java multithreading static locking

这是否意味着任何线程无论它获取的对象如何都不会干扰同步静态方法中执行的其他线程。即使我们使用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和主线程也不会进入该方法。 纠正我如果我错了。

3 个答案:

答案 0 :(得分: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) {...} }
    ...
}

但第二个显示了你的真实情况。

答案 1 :(得分:0)

如果线程t1进入静态方法,那么即使两者都有不同的对象,t2和主线程也不会进入该方法

它是一个static方法,它是该类的所有实例(对象)的 类级别 (常用)方法,因此,对象不会#39;重要。如果它声明为synchronized,则执行该方法的Thread将获取类对象的锁(Class<Test>对象)

static synchronized方法可以被认为如下

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

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

答案 2 :(得分:0)

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

类型的对象
相关问题