对的synchronized理解
  RuXuq8CpAyRj 2023年12月15日 67 0

对的synchronized理解_并发

你可以做这样的类比:

  • synchronized(对象) 中的对象,可以想象为一个房间(room),有唯一入口(门)房间只能一次进入一人进行计算,线程 t1,t2 想象成两个人
  • 当线程 t1 执行到 synchronized(room) 时就好比 t1 进入了这个房间,并锁住了门拿走了钥匙,在门内执行count++ 代码
  • 这时候如果 t2 也运行到了 synchronized(room) 时,它发现门被锁住了,只能在门外等待,发生了上下文切换,阻塞住了
  • 这中间即使 t1 的 cpu 时间片不幸用完,被踢出了门外(不要错误理解为锁住了对象就能一直执行下去哦),这时门还是锁住的,t1 仍拿着钥匙,t2 线程还在阻塞状态进不来,只有下次轮到 t1 自己再次获得时间片时才能开门进入
  • 当 t1 执行完 synchronized{} 块内的代码,这时候才会从 obj 房间出来并解开门上的锁,唤醒 t2 线程把钥匙给他。t2 线程这时才可以进入 obj 房间,锁住了门拿上钥匙,执行它的 count-- 代码

用图来表示

对的synchronized理解_synchronized_02

思考

synchronized 实际是用对象锁保证了临界区内代码的原子性,临界区内的代码对外是不可分割的,不会被线程切换所打断。

为了加深理解,请思考下面的问题

1.如果把 synchronized(obj) 放在 for 循环的外面,如何理解?-- 原子性

2.如果 t1 synchronized(obj1) 而 t2 synchronized(obj2) 会怎样运作?-- 锁对象

3.如果 t1 synchronized(obj) 而 t2 没有加会怎么样?如何理解?-- 锁对象

解答1:

从上图可以看出虽然i++只有一行代码,在底层其实是需要执行4行代码的

对的synchronized理解_并发_03

把 synchronized(obj) 放在 for 循环的外面

相当于锁住了for循环,for循环5000次i++,相当于执行了20000行代码,其实依旧是原子性的,最终结果依然是0

测试代码

public static void main(String[] args) throws InterruptedException {
        Room room = new Room();
        Thread t1 = new Thread(() -> {
            room.increment();
        }, "t1");

        Thread t2 = new Thread(() -> {
                room.decrement();
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("{}", room.getCounter());
    }
}

class Room {
    private int counter = 0;

    public synchronized void increment() {
        for (int i = 0; i < 5000; i++) {
            counter++;
        }
    }

    public synchronized void decrement() {
        for (int i = 0; i < 5000; i++) {
            counter--;
        }
    }

    public synchronized int getCounter() {
        return counter;
    }

输出结果

对的synchronized理解_synchronized_04

解答2:

这个是不行的,两个synchronized不是锁定同一个对象,当一个线程拿到锁,另一个线程也可以拿到锁,因为二者锁的对象不同,最终结果不为0。

测试代码

public static void main(String[] args) throws InterruptedException {
        Room room = new Room();
        Thread t1 = new Thread(() -> {
            room.increment();
        }, "t1");

        Thread t2 = new Thread(() -> {
            room.decrement();
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("{}", room.getCounter());
    }
}

class Room {
    private int counter = 0;
    private static Object o1 = new Object();
    private static Object o2 = new Object();

    public void increment() {
        synchronized (o1) {
            for (int i = 0; i < 5000; i++) {
                counter++;
            }
        }
        for (int i = 0; i < 5000; i++) {
            counter++;
        }
    }

    public void decrement() {
        synchronized (o2) {
            for (int i = 0; i < 5000; i++) {
                counter--;
            }
        }
    }

    public synchronized int getCounter() {
        return counter;
    }

输出

对的synchronized理解_并发_05

解答3:

t2线程没有加锁,在执行过程中并不会发生堵塞,而t1线程加锁,所以两个线程的代码并没有同步执行,所以是线程不安全的

测试代码

public static void main(String[] args) throws InterruptedException {
        Room room = new Room();
        Thread t1 = new Thread(() -> {
            room.increment();
        }, "t1");

        Thread t2 = new Thread(() -> {
            room.decrement();
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("{}", room.getCounter());
    }
}

class Room {
    private int counter = 0;
    private static Object o1 = new Object();

    public void increment() {
        synchronized (o1) {
            for (int i = 0; i < 5000; i++) {
                counter++;
            }
        }
    }

    public void decrement() {
        for (int i = 0; i < 5000; i++) {
            counter--;
        }
    }

    public synchronized int getCounter() {
        return counter;
    }

输出

对的synchronized理解_并发_06

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月15日 0

暂无评论

RuXuq8CpAyRj