一间大屋子有两个功能:睡觉、学习,互不相干
现在小南要学习,小女要睡觉,但如果只用一间屋子(一个对象锁)的话,那么并发度很低
细化前
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class BigRoom { public void sleep() { synchronized (this) { log.debug("sleeping 2 小时"); Sleeper.sleep(2); } } public void study() { synchronized (this) { log.debug("study 1 小时"); Sleeper.sleep(1); } } }
|
执行:
1 2 3 4 5 6 7 8
| BigRoom bigRoom = new BigRoom(); new Thread(() -> { bigRoom.compute(); },"小南").start();
new Thread(() -> { bigRoom.sleep(); },"小女").start();
|
某次结果:
1 2
| 12:13:54.471 [小南] c.BigRoom - study 1 小时 12:13:55.476 [小女] c.BigRoom - sleeping 2 小时
|
细化后
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class BigRoom { private final Object studyRoom = new Object(); private final Object bedRoom = new Object(); public void sleep() { synchronized (bedRoom) { log.debug("sleeping 2 小时"); Sleeper.sleep(2); } } public void study() { synchronized (studyRoom) { log.debug("study 1 小时"); Sleeper.sleep(1); } } }
|
1 2
| 12:15:35.069 [小南] c.BigRoom - study 1 小时 12:15:35.069 [小女] c.BigRoom - sleeping 2 小时
|
将锁的粒度细分