欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

synchronized(this)和synchronized(A.class)

程序员文章站 2022-06-02 08:13:47
...
  1. synchronized(this) 只能锁当前对象
  2. synchronized(A.class) 锁类,对类的所有实例生效
public class LockDemo{

    public void method1() {
        synchronized (this) {
            System.out.println("method1 start");
        }
    }

    public void method2() {
        synchronized (this) {
            System.out.println("method2 start");
        }
    }

}

-- 相当于--

public class LockDemo{

    public synchronized void method1() {
        System.out.println("method1 start");
    }

    public synchronized void method2() {
        System.out.println("method2 start");
    }

}

 

public class LockDemo{

    public void method1() {
        synchronized (LockDemo.class) {
            System.out.println("method1 start");
        }
    }

    public void method2() {
        synchronized (LockDemo.class) {
            System.out.println("method2 start");
        }
    }
}


-- 相当于--

public class LockDemo{

    public static synchronized void method1() {
        System.out.println("method1 start");
    }

    public static synchronized void method2() {
        System.out.println("method2 start");
    }
}

 

相关标签: