锁实例和锁类
synchronized锁实例:持有相同实例的多个线程互斥,持有不同实例的多个线程不互斥。
synchronized锁类:持有不同实例的多个线程也互斥。
什么叫持有实例的线程?
class Dog {
public void bark() {
synchronized(this) {
System.out.println(Thread.currentThread().getName() + " is barking");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
}
}
public class Test {
public static void main(String[] args) {
Dog dog1 = new Dog();
Dog dog2 = new Dog();
// 创建线程分别调用 dog1 和 dog2 的同步方法
Thread t1 = new Thread(() -> dog1.bark());
Thread t2 = new Thread(() -> dog2.bark());
t1.start();
t2.start();
}
}
可以看到Thread持有dog1和dog2实例。
这里的“持有实例”不是指线程本身拥有对象,而是指线程在执行同步代码块时,要获取的那个实例对象的锁。
普通方法锁
锁的是当前对象实例。相当于锁实例。
静态方法锁
锁的是当前类的 Class
对象。相当于锁类