【发布时间】:2015-02-19 03:24:10
【问题描述】:
是否可以在多个线程之间共享一个对象来模拟 Java 死锁场景?
例如我有一堂课
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',并且两个同步实例方法不能同时运行,这些事情让人相信我们不能在这里模拟死锁。我说的对吗?
【问题讨论】:
-
静态方法可以通过静态变量的形式访问
this(类似于单例模式)。
标签: java multithreading