我刚刚编译并运行了这个java程序,但输出并不令人愉快。 我不知道为什么线程处于死锁状态。 谁能帮我理解程序的输出。
class A {
synchronized void foo(B b) {
String name=Thread.currentThread().getName();
System.out.println(name+"entered A.foo");
try {
Thread.sleep(1000);
} catch(Exception e) {}
System.out.println(name+"trying to call B.last()");
b.last();
}
synchronized void last() {
System.out.println("inside A.last");
}
}
class B {
synchronized void bar(A a) {
String name=Thread.currentThread().getName();
System.out.println(name+"entered B.bar");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("b interrupted");
}
System.out.println(name+"trying to call A.last()");
a.last();
}
synchronized void last() {
System.out.println("inside A.last");
}
}
class DeadLock implements Runnable {
A a=new A();
B b=new B();
DeadLock() {
Thread.currentThread().setName("mainthread");
Thread t=new Thread(this,"racingthread");
t.start();
a.foo(b);
System.out.println("back in main thread");
}
public void run() {
b.bar(a);
System.out.println("back in other theread");
}
public static void main(String...d) {
new DeadLock();
}
}
我的计算机上的输出是
mainthreadentered A.foo
racingthreadentered B.bar
mainthreadtrying to call B.last()
racingthreadtrying to call A.last()
最佳答案
你遇到了典型的僵局。
A.foo()
锁定a
并调用b.last()
尝试锁定b
B.bar()
锁定b1
并调用a.last()
尝试锁定a
双方都无法继续,因为双方都需要对方的锁。
I don't know why the threads are in deadlock situation.
因为这就是你的程序的设计目的。
鉴于您不需要任何锁,最简单的解决方案是删除所有 synchronized
关键字。
关于java - 多线程中困惑的输出显示死锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12164274/