java - 在 java 中,这种死锁是否仅在同步块的情况下发生,而不是在同步方法的情况下发生?
问题描述
许多教程显示了死锁的代码,例如,
public class ResolveDeadLockTest {
public static void main(String[] args) {
ResolveDeadLockTest test = new ResolveDeadLockTest();
final A a = test.new A();
final B b = test.new B();
// Thread-1
Runnable block1 = new Runnable() {
public void run() {
synchronized (a) {
try {
// Adding delay so that both threads can start trying to
// lock resources
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Thread-1 have A but need B also
synchronized (b) {
System.out.println("In block 1");
}
}
}
};
// Thread-2
Runnable block2 = new Runnable() {
public void run() {
synchronized (b) {
// Thread-2 have B but need A also
synchronized (a) {
System.out.println("In block 2");
}
}
}
};
new Thread(block1).start();
new Thread(block2).start();
}
}
所以如果我们在那些锁定对象中使用 Synchronized 方法而不是这个类中的 Synchronized 块,那么死锁不会发生吗?
解决方案
推荐阅读
- swift - Swift - 基于不同尺寸设备的动作
- java - 使用扫描仪时找不到句子中的单词
- react-native - React Native - Scrollview 水平冻结
- c# - c# - MemoryMappedFile,MemoryMappedFileAccess.ReadExecute 做什么或者我应该什么时候使用它?
- django - 如何从数据库中为 Django Rest Framework 中的登录用户返回数据?
- android - 从 URI 创建一个可写的 DocumentFile
- ios - 错误域 = WebKitErrorDomain 代码 = 102 “帧加载中断”
- mysql - 如何从 mysql 表中获取该 id 的名称?
- ios - 如何在 Apple Pay 中集成订阅支付模式?
- python - 我怎样才能按键中断ctrl+c?