Synchronized同步锁,简单来说,使用Synchronized关键字将一段代码逻辑,用一把锁给锁起来,只有获得了这把锁的线程才访问。并且同一时刻,只有一个线程能持有这把锁,这样就保证了同一时刻只有一个线程能执行被锁住的代码,从而确保代码的线程安全。
每个Java对象都可以充当一个实现同步的锁,这些锁被称为内置锁或者监视器锁。
- synchronized(reference-to-lock) {
- //临界区
- }
解释:reference-to-lock就是锁的引用,任何一个Java对象都可以成为reference-to-lock.你可以实例化一个Object对象,将它作为锁。如果直接使用this,代表是当前对象作为锁。
Synchronized关键字的用法:
synchronized修饰实例方法,用到的锁,默认为this当前方法调用对象;
当使用synchronized修饰静态方法时,以下两种写法作用和意义相同:
- public class Foo {
- // 实例方法
- public synchronized void doSth1() {
- // 获取this锁,才能执行该方法
- }
-
- // 实例方法
- public void doSth2() {
- synchronized(this) {
- // 获取this锁,才能执行该代码块
- }
- }
- }
- public static void main(String[] args) {
- // 实例化一个对象
- Foo fa = new Foo();
-
- // 创建不同的线程1
- Thread thread01 = new Thread() {
- public void run() {
- // 使用相同的对象访问synchronized方法
- fa.doSth1();
- }
- };
-
- // 创建不同的线程2
- Thread thread02 = new Thread() {
- public void run() {
- // 使用相同的对象访问synchronized方法
- fa.doSth1();
- }
- };
-
- // 启动线程
- thread01.start();
- thread02.start();
- }
- public static void main(String[] args) {
- // 创建不同的对象(相同类型)
- Foo fa = new Foo();
- Foo fb = new Foo();
-
- // 创建不同线程1
- Thread thread01 = new Thread() {
- public void run() {
- // 使用不同的对象访问synchronized方法
- fa.doSth2();
- }
- };
-
- // 创建不同线程2
- Thread thread02 = new Thread() {
- public void run() {
- // 使用不同的对象访问synchronized方法
- fb.doSth2();
- }
- };
-
- // 启动线程
- thread01.start();
- thread02.start();
- }
- public class Foo {
- // 静态方法
- public synchronized static void doSth1() {
- // 获取当前对象的Class对象锁,才能执行该方法
- }
-
- // 实例方法
- public static void doSth2() {
- synchronized(this.getClass()) {
- // 获取当前对象的Class对象锁,才能执行该代码块
- }
- }
- }
- synchronized(自定义对象) {
- //临界区
- }
在没有枷锁的情况下,所有的线程都可以自由的访问对象中的代码,而synchronized关键字只是限制了线程对于其他已经枷锁的同步代码块的访问,并不会对其他代码做限制。所以,同步代码块应该是越小越好。