2013-07-30 25 views
2

在鍛鍊爲什麼我的線程沒有被通知?

做一個計劃,使你有一個時尚和一臺縫紉機,所以操作員輸入數據 的寬度和高度,以履行其工作通知縫紉機。

Operator接收數據並處理並通知機器。 Machine接收數據並完成該過程。

但是,當我運行時,Maquina線程未被通知,機器和Operator處於無限循環接收數據。

public class Operator extends Thread { 

    Scanner in = new Scanner(System.in); 
    int altura, largura; 
    public void run() { 
     while(true) { 
      synchronized (this) { 
       System.out.print("Altura: "); 
       altura = in.nextInt(); 
       System.out.print("Largura: "); 
       largura = in.nextInt(); 
       notify(); 
      } 
     } 
    } 

    public String getForma() { 
     return "Forro de mesa : " + (altura * largura); 
    } 
} 

public class Maquina extends Thread{ 

    private Operator c; 

    public Maquina(Operator c) { 
     this.c = c; 
    } 


    public void run() { 
     while(true) { 
      synchronized (c) { 
       try { 

        System.out.println("Waiting shape..."); 
        c.wait(); 

        System.out.println("init drawn..."); 
        Thread.currentThread().sleep(3000); 

        System.out.println("drawing..."); 
        Thread.currentThread().sleep(3000); 

        System.out.println(c.getForma() + ", finalized"); 

       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 
+0

有什麼問題嗎?你問爲什麼它循環? – Gray

+0

總是在循環中而不是通知線程機器。 從我的理解,應該收到來自用戶的數據,並在我收到數據時傳遞給機器 – diegohsi

回答

1

在運行您的代碼時,問題似乎是"Waiting shape..."郵件從未達到。這令我感到驚訝,但似乎while (true) { synchronized(c)永遠不會讓Maquina進入​​區塊。

Operator.run()方法的前面添加一個小睡眠可以解決問題。它給了Maquina獲得鎖定的時間並輸入wait()

while (true) { 
    try { 
     Thread.sleep(100); 
    } catch (InterruptedException e) { 
     Thread.currentThread().interrupt(); 
     return; 
    } 
    synchronized (this) { 
     System.out.print("Altura: "); 
     altura = in.nextInt(); 
     System.out.print("Largura: "); 
     largura = in.nextInt(); 
     notify(); 
    } 
} 
+0

灰色,但'操作員'永遠不會釋放鎖...這是原因嗎? wait()立即釋放鎖定的對象,但是notify()不是?可以嗎? –

+0

'Operator'在離開'synchronized {}'塊時釋放了鎖。該循環在該塊的外側。 – Gray

+0

Gray,我不明白爲什麼會發生這種情況,wait()線程在離開同步塊後應該獲得鎖定,不是嗎?爲什麼我們需要把脾氣?時間是不夠的,以扭轉鎖定? –

相關問題