synchronized 加在实例方法上锁的是什么对象
当 synchronized 关键字直接修饰一个非静态(实例)方法时,它锁定的是当前调用该方法的对象实例,即 this 指针指向的内存地址。这意味着每个对象实例都有自己独立的监视器锁(monitor),不同实例之间的方法调用互不干扰,只有同一个实例上的同步方法才会发生阻塞竞争。

public class Account {
private double balance;
// 同步实例方法,锁住 this
public synchronized void deposit(double amount) {
balance += amount;
}
// 同步实例方法,锁住 this
public synchronized void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
}
}
public double getBalance() {
return balance;
}
}
// 使用示例
Account account1 = new Account();
Account account2 = new Account();
// 线程 A 操作 account1
new Thread(() -> account1.deposit(100)).start();
// 线程 B 操作 account2
// 注意:这里不会与线程 A 竞争锁,因为 account1 != account2
new Thread(() -> account2.withdraw(50)).start();在上述代码中,deposit 和 withdraw 都是实例同步方法。如果两个线程分别操作 account1 和 account2,它们获取的是不同的锁,因此可以并发执行。但如果两个线程都操作 account1,则必须排队执行,因为它们在争夺同一把锁——account1 对象的监视器。
synchronized 加在静态方法上锁的是什么对象
当 synchronized 关键字修饰一个静态方法时,它锁定的是该方法所属类的 Class 对象,即 ClassName.class。Class 对象在 JVM 中是全局唯一的,因此静态同步方法在整个类的所有实例之间共享同一把锁。这确保了无论创建了多少个实例,对静态资源的访问都是互斥的。

立即学习“Java免费学习笔记(深入)”;
public class SingletonManager {
private static int instanceCount = 0;
// 同步静态方法,锁住 SingletonManager.class
public static synchronized void createInstance() {
instanceCount++;
System.out.println("Created instance " + instanceCount);
}
public static int getCount() {
return instanceCount;
}
}
// 使用示例
// 无论哪个线程调用,锁的都是 SingletonManager.class
new Thread(() -> SingletonManager.createInstance()).start();
new Thread(() -> SingletonManager.createInstance()).start();在这个例子中,createInstance 是静态同步方法。即使有多个线程同时调用它,或者通过不同的实例(虽然静态方法通常不依赖实例)调用,它们也必须竞争同一把锁,即 SingletonManager.class 对象的监视器。这保证了 instanceCount 的递增操作是原子性的,不会出现计数错误。
实例方法与静态方法同时存在时的锁竞争关系
当一个类中既包含同步实例方法又包含同步静态方法时,它们分别锁定不同的对象:实例方法锁 this,静态方法锁 Class 对象。因此,这两个方法是完全独立、互不阻塞的。线程可以在执行同步实例方法的同时,另一个线程执行同步静态方法,两者不会发生死锁或竞争。
public class MixedSyncExample {
private int instanceVar = 0;
// 锁住 this
public synchronized void instanceMethod() {
instanceVar++;
try { Thread.sleep(100); } catch (InterruptedException e) {}
System.out.println("Instance method done, var: " + instanceVar);
}
// 锁住 MixedSyncExample.class
public static synchronized void staticMethod() {
try { Thread.sleep(100); } catch (InterruptedException e) {}
System.out.println("Static method done");
}
}
// 测试代码
MixedSyncExample obj = new MixedSyncExample();
Thread t1 = new Thread(() -> obj.instanceMethod());
Thread t2 = new Thread(() -> MixedSyncExample.staticMethod());
// 这两个线程几乎可以同时运行,因为它们锁的是不同的对象
t1.start();
t2.start();
t1.join();
t2.join();运行上述测试代码,你会发现 instanceMethod 和 staticMethod 的输出几乎是交替或同时出现的,因为它们的锁机制互不影响。理解这一点对于设计多线程安全的类至关重要,避免误以为所有 synchronized 方法都会互相阻塞。


















