锁的粒度粗细
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();
}
}
}
}
将锁的粒度细分
- 好处,是可以增强并发度
- 坏处,如果一个线程需要同时获得多把锁,就容易发生死锁