【Java】解析synchronized中的锁对象

锁对象

先看一下Java中是如何定义对象的。在Java虚拟机中,对象在内存中的结构可以划分为4部分区域:
🟢markword
🟢类型指针(_class)
🟢实例数据(instance_data)
🟢对齐填充(padding)
其中前两个在对象头中,实例数据表示类中的属性,对齐填充代表每一个类的对象占用的字节数必须是8字节的整数倍。Java中的对象都包含一个叫对象头的部分,其中markword区域主要描述了当前是哪个线程获取到了锁资源,记录的是线程对象信息,当线程释放锁资源的时候就会把线程对象信息清除掉,其他线程就可以继续获取锁资源。

常见的几种情况

我们定义两个线程分别实现自增50000次,使用不同的锁对象,看最终结果能否达到预期。
1、定义一个自增操作对象调用一个自增方法,里面要竞争的锁对象是同一个this,此时可以达到预期。

public class Demo01_Synchronized {
    // 定义自增操作的对象
    private static Counter2 counter = new Counter2();

    public static void main(String[] args) throws InterruptedException {
        // 定义两个线程,分别自增5万次
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increment();
            }
        });

        // 启动线程
        t1.start();
        t2.start();
        // 等待自增完成
        t1.join();
        t2.join();
        // 打印结果
        System.out.println("count = " + counter.count);

    }
}
class Counter2 {
    public static int  count = 0;
    // 自增方法
    public synchronized void increment () {
        count++;
    }
}

2、定义两个自增操作对象在调用同一个自增方法时,里面要竞争的this并不是同一个对象,不会产生锁竞争关系,得不到预期结果。

public class Demo04_Synchronized {
    // 定义自增操作的对象
    private static Counter4 counter = new Counter4();
    private static Counter4 counter1 = new Counter4();

    public static void main(String[] args) throws InterruptedException {
        // 定义两个线程,分别自增5万次
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter1.increment();
            }
        });

        // 启动线程
        t1.start();
        t2.start();
        // 等待自增完成
        t1.join();
        t2.join();
        // 打印结果
        System.out.println("count = " + counter.count);

    }
}
class Counter4 {
    public static int count = 0;
    // 自增方法
    public synchronized void increment () {
        count++;
    }
}

3、自定义一个对象来充当锁对象的角色,用一个自增操作对象来调用自增方法可以得到预期结果。

public class Demo05_Synchronized {
    // 定义自增操作的对象
    private static Counter5 counter = new Counter5();
    public static void main(String[] args) throws InterruptedException {
        // 定义两个线程,分别自增5万次
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increment();
            }
        });

        // 启动线程
        t1.start();
        t2.start();
        // 等待自增完成
        t1.join();
        t2.join();
        // 打印结果
        System.out.println("count = " + counter.count);

    }
}
class Counter5 {
    public static int count = 0;
    //定义一个对象来充当锁对象的角色
    Object locker = new Object();
    // 自增方法
    public void increment () {
        synchronized (locker){
            count++;
        }
    }
}

4、在3的基础上定义两个自增操作对象分别调用自增方法,不能得到预期结果,原因在于locker对象作为成员变量每次new的时候都会初始化一次,得到的locker对象不是同一个对象,不会发生锁竞争关系。

public class Demo05_Synchronized {
    // 定义自增操作的对象
    private static Counter5 counter = new Counter5();
    private static Counter5 counter1 = new Counter5();
    public static void main(String[] args) throws InterruptedException {
        // 定义两个线程,分别自增5万次
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter1.increment();
            }
        });

        // 启动线程
        t1.start();
        t2.start();
        // 等待自增完成
        t1.join();
        t2.join();
        // 打印结果
        System.out.println("count = " + counter.count);

    }
}
class Counter5 {
    public static int count = 0;
    //定义一个对象来充当锁对象的角色
    Object locker = new Object();
    // 自增方法
    public void increment () {
        synchronized (locker){
            count++;
        }
    }
}

5、在4的基础上,用static修饰locker对象,此时可以得到预期的结果。原因在于static修饰的类成员,随着类初始化的时候全局唯一,这样每new一个自增操作的对象时访问的是同一个locker,存在锁竞争关系,能得到正确结果。

public class Demo05_Synchronized {
    // 定义自增操作的对象
    private static Counter5 counter = new Counter5();
    private static Counter5 counter1 = new Counter5();
    public static void main(String[] args) throws InterruptedException {
        // 定义两个线程,分别自增5万次
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter1.increment();
            }
        });

        // 启动线程
        t1.start();
        t2.start();
        // 等待自增完成
        t1.join();
        t2.join();
        // 打印结果
        System.out.println("count = " + counter.count);

    }
}
class Counter5 {
    public static int count = 0;
    //定义一个对象来充当锁对象的角色
    private static Object locker = new Object();
    // 自增方法
    public void increment () {
        synchronized (locker){
            count++;
        }
    }
}

6、使用类对象充当锁对象也会产生锁竞争,因为类对象是全局唯一的。

public class Demo06_Synchronized {

    // 定义自增操作的对象
    private static Counter6 counter = new Counter6();
    private static Counter6 counter1 = new Counter6();

    public static void main(String[] args) throws InterruptedException {
        // 定义两个线程,分别自增5万次
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                // 调用加锁的方法
                counter.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                // 调用没有加锁的方法
                counter1.increment();
            }
        });

        // 启动线程
        t1.start();
        t2.start();
        // 等待自增完成
        t1.join();
        t2.join();
        // 打印结果
        System.out.println("count = " + counter.count);

    }
}

class Counter6 {
    public static int count = 0;

    public void increment() {
        // 使用Counter6类对象充当锁对象
        synchronized (Counter6.class) {
            // 要执行的修改逻辑
            count++;
        }
    }
//    public void increment() {
//        // 使用String类对象充当锁对象
//        synchronized (String.class) {
//            // 要执行的修改逻辑
//            count++;
//        }
//    }
}

总结

在多线程环境中,保证多个线程之间竞争的锁对象是同一个即可,锁对象可以是Java中的任何对象。需要重点要理解,synchronized 锁的是什么.?两个线程竞争同一把锁,才会产生阻塞等待;两个线程分别尝试获取两把不同的锁, 不会产生竞争
在这里插入图片描述


继续加油~
在这里插入图片描述

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值