死锁问题是多线程特有的问题。下面利用Java语言模拟死锁。
class A {
public synchronized void foo(B b) {
try {
Thread.sleep(200); //确保死锁一定发送
} catch (InterruptedException e) {
e.printStackTrace();
}
b.last();
}
public synchronized void last() {}
}
class B {
public synchronized void bar(A a) {
try {
Thread.sleep(200); //确保死锁一定发送
} catch (InterruptedException e) {
e.printStackTrace();
}
a.last();
}
public synchronized void last() {}
}
public class TestDeadLock implements Runnable {
A a = new A();
B b = new B();
@Override
public void run() {
b.bar(a);
}
public void init() {
a.foo(b);
}
public static void main(String[] args) {
TestDeadLock tdl = new TestDeadLock();
new Thread(tdl).start();
tdl.init();
}
}
上述代码中,有两个线程:主线程、TestDeadLock线程。首先TestDeadLock线程调用b.bar(a),此时对B进行加锁,同时主线程调用a.foo(b)方法,该方法对A进行加锁。在sleep(200)后,A企图对B进行加锁,B企图对A进行加锁,这样就产生了死锁。
全文完。转载请注明出处。

1514

被折叠的 条评论
为什么被折叠?



