2015-04-06 62 views
0

我正在實現一個SimpleInterThreadCommunication的簡單例子,並使用了wait和notify。爲什麼我在使用wait和notify的javaInterThread通信中出現錯誤?

我在線程間總類得到一個錯誤任何人都可以解釋爲什麼

public class InterThread 

{ 

public static void main(String s[])throws InterruptedException 

{ 

    Thread b=new Thread(); 

    b.start(); 

    Thread.sleep(10); 

    synchronized (b) 

    { 

    System.out.println("Main thread trying to call wait"); 

    b.wait(); 

    System.out.println("Main thread got notifies"); 

    System.out.println(b.total); //error here total cannot be resolved to a field 

    } 

} 

} 

class ThreadB extends InterThread 

{ 

    int total=0; 

    public void run() 

    { 

     synchronized(this) 

     { 

      System.out.println("child thread got notifies"); 

      for(int i=0;i<3;i++) 

      { 

       total=total+i; 

      } 

      System.out.println("child thread ready to give notification"); 

       this.notify(); 
     } 

    } 

} 
+1

這是因爲你的對象b是線程類的,並且總體字段沒有在線程類中隱式定義,而是你已經在ThreadB類中定義了變量b。因此它不能被解析爲一個變量。 – CoderNeji 2015-04-06 13:21:30

+0

因爲'Thread'沒有一個名爲'b'的公共字段。 – 2015-04-06 13:23:02

+1

btw。線程通信可以通過java.util.concurrent中的類以更簡單,更可靠的方式完成。例如LinkedTransferQueue – SpiderPig 2015-04-06 13:47:57

回答

1

您需要創建ThreadB類的對象,那麼你可以訪問總場。 對於Thread類對象不可見。

您已經創建b對象Thread類和Thread類沒有任何這樣的字段命名爲total可用。

改變你的代碼類似下面:

ThreadB b1=new ThreadB(); 
    System.out.println(b1.total); 
+0

爲什麼我現在沒有得到總計作爲輸出我的輸出:子線程得到通知 子線程準備給通知 主線程試圖調用等待 – 2015-04-06 13:43:32

+1

你需要改變你的順序通知和等待。你先打電話通知,然後等待,反之亦然。因爲如果一個線程正在等待,那麼其他線程應該通知它。如果沒有其他線程會調用notify,那麼你的線程可能會永遠等待,這就是爲什麼在調用wait()之後沒有任何事情發生 – Prashant 2015-04-06 13:46:09

0

回答我從樂於助人的人 這裏建議後所做的更改是更正後的代碼

公共類線程間

{

公衆static void main(String s [])throws InterruptedException

{

ThreadB b=new ThreadB(); //correction 1 

b.start(); 

Thread.sleep(10); 

synchronized (b) 

{ 

    System.out.println("Main thread trying to call wait"); 

    b.notify(); //correction2 

    System.out.println("Main thread got notifies"); 

System.out.println(b.total); 

}

}

}

類ThreadB延伸線程間

{

int total=0; 

public void run() 

{ 

    synchronized(this) 

    { 

     System.out.println("child thread got notifies"); 

     for(int i=0;i<3;i++) 

     { 

      total=total+i; 

     } 

     System.out.println("child thread ready to give notification"); 

    try 

     { 

     System.out.println("child thread ready trying to call wait"); 

     this.wait(); //corrected 3 

     } 

     catch(InterruptedException e) 

     { 

      System.out.println("interrupted Exception"); 

     } 

    } 

} 

}

相關問題