锁的粒度粗细

锁的粒度粗细

1.锁住不同的对象会有不同的效率

1.锁住大对象,会造成低并发程度

/**
 * 直接锁大对象
 */
@Slf4j(topic = "c.BigRoom")
class BigRoom {
    public void sleep() {
        synchronized (this) {	//直接锁住当前对象
            log.debug("睡觉2小时");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void study() {
        synchronized (this) {
            log.debug("学习3小时");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

2.锁住小对象,并发程度高

/**
 * 优化
 * 加2个不同的锁
 */
@Slf4j(topic = "c.BigRoom2")
class BigRoom2 {
    private static final Object studyRoom = new Object();
    private static final Object sleepRoom = new Object();

    public void sleep() {
        synchronized (studyRoom) {	//锁住小对象,不是当前对象
            log.debug("睡觉2小时");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void study() {
        synchronized (sleepRoom) {
            log.debug("学习3小时");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述
将锁的粒度细分

  • 好处,是可以增强并发度
  • 坏处,如果一个线程需要同时获得多把锁,就容易发生死锁
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值