本文介绍了当线程在同步块内崩溃时,锁会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 Thread-1 在对象上同步

同步(对象){//语句1//语句2//语句3}

如果 Thread-1 在 statement2 上崩溃,对象上的锁会发生什么情况,当这种情况发生时,JVM 会自动释放 Thread-1 上的锁吗?因为否则如果 Thread-2 正在等待释放对象上的锁并且 Thread-1 崩溃,则 Thread-2 将永远等待.

解决方案

定义在JLS #14.19:

同步(表达式)块

如果块的执行由于任何原因突然完成,则监视器被解锁并且同步语句由于同样的原因突然完成.

lets say Thread-1 synchronizes on object

synchronize(object){
  //statement1
  //statement2
  //statement3
}

what happens to the lock on object if Thread-1 crashes on statement2, will JVM release the lock on Thread-1 automatically when this happens ? because otherwise if Thread-2 is wating for the lock on object to be released and Thread-1 crashes, the Thread-2 will wait forever.

解决方案

It is defined in the JLS #14.19:

synchronized ( Expression ) Block

这篇关于当线程在同步块内崩溃时,锁会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:13
查看更多