是否可以在多个线程之间共享一个对象来模拟Java死锁场景?
例如,我有一个 class
public class MyClass {
public synchronized void syncInstanceMethod1(){
/// Anything here to simulate a dead lock
}
public synchronized void syncInstanceMethod2(){
/// Anything here to simulate a dead lock
}
public static synchronized void syncStaticMethod1(){
/// Anything here to simulate a dead lock
}
public static synchronized void syncStaticMethod2(){
/// Anything here to simulate a dead lock
}
public void instanceMethod1(){
/// Anything here to simulate a dead lock
}
public void instanceMethod2(){
/// Anything here to simulate a dead lock
}
public static void main(String[] args) {
MyClass shared = new MyClass(); // Allowed to create only one instance
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
// Do whatever here to simulate dead lock like calling various methods on the shared object in any order
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
// Do whatever here to simulate dead lock like calling various methods on the shared object in any order
}
});
// Allowed to create more threads like above. t3 , t4 etc...
t1.start();
t2.start();
}
}
可能是不可能的 . 由于可能发生死锁的常见情况是代码块,它获取锁定一个对象而不释放它尝试获取另一个对象的锁定 .
我们可以通过调用静态同步方法从同步实例方法之一模拟这种情况,即在锁定'this'时试图锁定'class'对象 . 但是为了发生僵局,我们需要在其他地方以相反的顺序出现类似的情况 .
另外,由于静态方法无法访问'this'它无法锁定'this'并且两个同步实例方法无法同时运行,这些事情使得我们无法模拟死锁 . 我对么?