类锁和对象锁
2021-06-21/2021-06-21
1. 对象锁
修饰在非静态方法或者锁对象为普通对象。
多个线程调用同一个对象的同步方法会阻塞,调用不同对象的同步方法不会阻塞。(java 对象的内存地址是否相同)
1// 非静态方法
2public synchronized void obj3() {
3
4}
5
6// 普通对象
7synchronized (this) {
8
9}
2. 类锁
修饰静态方法或锁对象为 class
无论多少个对象, 共享同一个锁(锁定在该类的 class 上或者是 classloader 对象上),保障同一个时刻多个线程同时访问同一个 synchronized 块,当一个线程在访问时,其他的线程等待。
1// 静态方法
2public static synchronized void obj3() {
3
4}
5
6// 锁对象为 class
7synchronized (test.class) {
8
9}