2
4. synchronized工作原理
source link: http://sunliangliang.com/?p=43
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
4. synchronized工作原理
1.入门知识回顾
synchronized可以作用在对象实例和,类两者的区别
2.底层原理
核心原理是
monitorenter
和monitorexit
两个指令
- synchronized加锁的对象,都会有一个
monitor
计数器,从0开始,如果一个线程要获取monitor的锁,需要判定该值是否为0,若为0,则获取到锁,并将值+1,此时monitor=1.jvm会记录持有该锁的线程。 - 并且
monitor
锁是可重入的,原理就是,获取锁的时候如果monitor不是1,会判定持有该锁的是否为当前线程,如果是的话对计数器是自增操作,此时monitor=2。 - 如果出了
synchronized
修饰的代码片段,就会有一个monitorexit
的指令,在底层会对monitor
的计数器减一,如果多次重入就会对应多次减一,直到计数器是0
坚持有质量的创作,您的支持将支持我继续创作!
- 本文作者: 阿亮
- 本文链接: http://sunliangliang.com/?p=43
- 版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0 许可协议。转载请注明出处!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK