java 线程创建后,synchronized 通过获取和释放对象监视器锁(monitor lock)来保证共享变量安全。具体做法是在访问共享变量的代码块或方法前加上 synchronized 关键字,确保同一时刻只有一个线程能持有该对象的锁并执行临界区代码,从而避免数据竞争。这样做会强制线程在修改共享状态前进行内存屏障操作,将工作内存中的脏数据刷新到主内存,并从主内存重新加载最新值,保证了可见性;同时,互斥的锁机制确保了操作的原子性。

synchronized 修饰实例方法时锁的对象是谁
当 synchronized 修饰非静态实例方法时,锁的对象是当前实例本身,即 this 对象。这意味着如果两个线程调用同一个对象的不同同步方法,它们会竞争同一把锁,导致串行化执行;但如果调用不同对象的同步方法,则互不影响。这种设计使得每个实例拥有独立的监视器,适合保护实例级别的共享状态。

public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final Count: " + counter.getCount());
}
}
上述代码中,increment 和 getCount 都是同步方法,锁对象为 counter 实例。运行结果应为 Final Count: 2000,因为两个线程对同一对象的 count 变量进行了安全的并发递增。若去掉 synchronized,结果可能小于 2000,因为存在竞态条件。
立即学习“Java免费学习笔记(深入)”;
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
synchronized 修饰静态方法时锁的对象是谁
当 synchronized 修饰静态方法时,锁的对象是该方法所属类的 Class 对象,例如 Counter.class。这表示所有该类的实例都会共享这把锁,即使在不同实例上调用静态同步方法,也会发生互斥。这种机制适用于保护类级别的共享资源,如单例模式中的初始化逻辑或全局计数器。

public class StaticCounter {
private static int count = 0;
public static synchronized void increment() {
count++;
}
public static synchronized int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final Count: " + getCount());
}
}
此代码中,increment 和 getCount 是静态同步方法,锁对象为 StaticCounter.class。无论创建多少个 StaticCounter 实例,所有线程访问这些方法时都受同一把锁保护。运行结果同样为 Final Count: 2000。若改为非静态方法但使用 static synchronized,则锁范围扩大至类级别,影响所有实例间的并发。
多个线程同时调用同一对象的同步方法会发生什么
多个线程同时调用同一对象的同步方法时,只有持有锁的线程能进入临界区,其他线程必须阻塞等待,直到锁被释放。这种互斥机制确保了共享变量的读写操作不会交错,从而维持数据一致性。即使方法内部逻辑简单,如自增操作,由于涉及读-改-写三步,不加锁会导致中间状态被其他线程读取,引发数据丢失。

















