2012-08-28 30 views
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() 
+0

這功課嗎?如果需要,請添加標籤。 – Gray

回答

5

你有一個典型的死鎖。

  • A.foo()a並調用b.last()其試圖鎖定b
  • B.bar()b1並調用a.last()其試圖鎖定a

也不能繼續進行,因爲每個需要其他的鎖定。

我不知道爲什麼線程處於死鎖狀態。

因爲這就是你的程序設計的目的。


給你不需要任何鎖的,最簡單的解決方法是刪除所有​​關鍵字。

+0

我很困惑,通過調用對象裁判的方法鎖定對象?在調用A.foo() – kTiwari

+0

雅去除synchroziation將有助於運行中的所有方法,但發生了什麼事我刪除從方法 – kTiwari

+1

@krishna所有同步關鍵字Chandra:在對象上調用一個'synchronized'方法將嘗試獲取該對象上的鎖。 – Tudor

0

由於對象B被鎖定在foo()bar()a,所以當你調用last()每個功能正在等待對方釋放鎖。導致死鎖

0

看起來像功課。但我會說,答案是你在deadlock()的構造函數中設置了另一個線程。

這兩個線程都會競爭,並且可能會鎖定在其中一個同步方法上,因爲您正在使用計時器來使它們一致。我的猜測是沒有運行它。

另外類名應該是大寫。

0

死鎖沒有解決方案。程序員必須小心謹慎,不要發生死鎖。