2

我刚刚编译并运行了这个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()
4

4 回答 4

5

你有一个经典的僵局。

  • A.foo()尝试锁定的锁a和调用b.last()b
  • B.bar()尝试锁定的锁b1和调用a.last()a

两者都不能继续,因为每个人都需要对方的锁。

我不知道为什么线程处于死锁状态。

因为这就是你的程序设计的目的。


鉴于您不需要任何锁,最简单的解决方案是删除所有synchronized关键字。

于 2012-08-28T17:23:26.577 回答
0

There is no solution for Deadlock. Programmer has to take care and code in such a way that deadlock should not occur.

于 2012-08-28T19:37:30.690 回答
0

由于对象 b 一直被锁定bar(),因此当您调用每个函数时,都a在等待另一个释放锁定。这导致了僵局foo()last()

于 2012-08-28T17:20:31.150 回答
0

看起来像家庭作业。但我想说的答案是你在 deadlock() 的构造函数中设置了另一个线程。

两个线程都将竞争并且可能被锁定在同步方法之一上,因为您正在使用计时器使它们对齐。是我的猜测没有运行它。

类名也应该是大写的。

于 2012-08-28T17:20:51.930 回答