java synchronized关键字用法
文章目录
- 前置
- 用法:sync 方法
- 用法:sync static 方法
- 用法:sync 同步代码块
前置
synchronized 作用:
它为了解决多线程环境下资源的竞争问题。通过互斥锁机制,确保同一时间只有一个线程可以执行同步的代码
线程对共享变量的修改会立即刷新到主内存中,其他线程可以立即看到最新的值
用法:sync 方法
锁对象:当前实例对象(this)
public class Counter {private int count = 0;// 同步实例方法:锁对象是当前实例(this)public synchronized void increment() {count++;}public int getCount() {return count;}
}
用法:sync static 方法
锁对象:当前类的 Class 对象(如 MyClass.class)
public class StaticCounter {private static int count = 0;// 同步静态方法:锁对象是类的 Class 对象(StaticCounter.class)public static synchronized void increment() {count++;}public static int getCount() {return count;}
}
用法:sync 同步代码块
锁对象:可以灵活指定(如 this、Class 对象或自定义对象)
public class Counter {private int count = 0;// 自定义锁对象private final Object lock = new Object();public void increment() {// 同步代码块:锁对象是 locksynchronized (lock) {count++;}}public int getCount() {return count;}
}