2013-07-04 53 views
1

你好傢伙這是我的代碼,面臨的問題是,儘管調用了notifyAll,它並沒有釋放鎖,請你說明原因並告訴解決方案。對線程來說是新的。提前致謝。在java中釋放鎖對象

class Lock1 {} 

class Home1 implements Runnable { 
private static int i = 0; 

private Lock1 object; 
private Thread th; 

public Home1(Lock1 ob, String t) { 

    object = ob; 
    th = new Thread(this); 
    th.start(); 
} 

public void run() { 
    synchronized (object) { 

     while (i != 10) { 
      ++i; 
      System.out.println(i); 
     } 
     try { 
      // System.out.println("here"); 
      object.wait(); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 

     } 
     System.out.println("here thread 1"); 
    } 
} 
} 

class Home2 implements Runnable { 
private static int i = 0; 

private Lock1 object; 
Thread th; 

public Home2(Lock1 ob, String t) { 

    object = ob; 
    th = new Thread(this); 
    th.start(); 
} 

public void run() { 
    synchronized (object) { 

     while (i != 10) { 
      ++i; 
      System.out.println(i); 
     } 
     try { 
      // System.out.println("here"); 
      object.wait(); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 

     } 
     System.out.println("here thread 2"); 

    } 
} 

    } 

public class Locking { 

public static void main(String arg[]) { 
    Lock1 ob = new Lock1(); 

    new Home1(ob, "thread 1"); 
    new Home2(ob, "thread 2"); 
    synchronized (ob) { 
     ob.notifyAll(); 
    } 
} 

} 
+1

嗨 - 你能否提供一個更詳細的解釋,說明你試圖用你的代碼實現什麼? – robjohncox

+1

我不明白爲什麼你有重複的類「Home1」和「Home2」?你究竟想要達到什麼目標? – Multithreader

+0

我只是玩線程,在這裏試圖釋放所有的鎖,並完成程序的執行。這裏執行沒有完成。 –

回答

6

當您使用notifyAll的,你也應該有一個狀態改變,當您使用的等待,你應該檢查狀態變化。

在你的情況下,很可能在線程真的有時間開始之前很久就會調用notifyAll。 (對於一臺電腦,啓動一個線程需要一個永恆的時間,比如10,000,000個時鐘週期)。這意味着notifyAll會丟失。 (它只是通知當前實際正在等待的線程)

+0

另一個很好的答案; +1,公理。 – Bathsheba

+1

先生以任何方式完成執行?我應該在通知被調用之前把一些'sleep()'放到主線程中嗎? –

+0

是的,它的工作! 絕對正確的解釋。 –