静态同步方法提供了类级别的锁定.类级别锁定是什么意思? [英] Static Synchronized method provides Class level lock. What does Class Level Lock means?

查看:104
本文介绍了静态同步方法提供了类级别的锁定.类级别锁定是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does it mean that any Thread irrespective of the object it obtain will not interfere other Thread executing in Synchronized static method. Even if we call with 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和主线程将不会进入该方法,即使两者具有不同的对象. 纠正我,如果我错了.

If Thread t1 enters static method then t2 and main thread will not enter the method even though both have different object. Correct me If I am wrong.

推荐答案

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

具有一个static方法,这是该类的所有实例(对象)的 类级别 (常见)方法,因此,对象不会事情.如果将其声明为synchronized,则将执行该方法的线程将获取对类对象(Class<Test>对象)的锁定

its a static method, which is a class level (common) method to all the instances (objects) of that class, hence, objects doesn't matter. If its declared as synchronized, then the Thread which will execute the method will acquire the lock on the class object (Class<Test> object)

一种static synchronized方法可以像下面这样

a static synchronized method can be thought of like below

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

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

Since a class gets loaded once (unless you define your custom class-loader and re-load the class), there will be only one class object, which acts as lock for mutual exclusion

这篇关于静态同步方法提供了类级别的锁定.类级别锁定是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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