面试题:在静态方法和非静态方法上加 Synchronized的区别

在静态方法和非静态方法上加 Synchronized的区别

非静态方法

class Test{
public synchronized void test() {
    }
}
等价于
class Test{
public void test() {
synchronized(this) {
    }
  }
}
非静态方法:给对象加锁,这时候,在其他一个以上线程中执行该对象的这个同步方法(注意:是该对象)就会产生互斥

在静态方法

class Test{
public synchronized static void test() {
  }
}
等价于
class Test{
public static void test() {
synchronized(Test.class) {
    }
    }
}
静态方法: 相当于在类上加锁, 这时候,只要是这个类产生的对象,在调用这个静态方法时都会产生互斥
原文地址:https://www.cnblogs.com/dalianpai/p/14205107.html