2014-02-27 66 views
0

我想用在矢量運行的線程同步拋出:IllegalMonitorStateException螺紋

我嘗試等待拖車梅索德一個和其他notfiy

我想從靜態類 這是我的線程代碼中調用notify方法:

import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.Scanner; 
import java.util.Vector; 


public class TSend extends Thread { 

    Vector<String> File_Message=new Vector<String>(); 


     public void save_out_putMessage(String out_Msg){ 

      synchronized(this.File_Message){ 
     this.File_Message.add(out_Msg); 
     this.File_Message.notify(); 

     } 

     } 


public synchronized String GetMessage() throws InterruptedException{ 
     String message; 
     while(File_Message.size()==0){ 
      this.File_Message.wait(); 
     } 

     message = File_Message.get(0); 
     File_Message.removeElementAt(0); 
     return message; 
} 


public synchronized void Recepteur_de_Message (String message){ 

    /* 
    * Pour savgarde tout les message des client dans un vecteur Message . 
    * 
     */ 
    File_Message.add(message); 

    notify(); 

} 


@Override 
public void run(){ 
    try{ 
      String Message ; 
      while(true){ 
       str =GetMessage(); 
      } 
    }catch(Exception e){ 
      e.printStackTrace(); 
    } 

,我嘗試這樣做:

synchronized(F){ 
    while(F.size()==0) { 
     F.wait(); 
    } 

    Message= new String(F.get(0)); 
    F.removeElementAt(0); 
} 

但我有這個excption婉我嘗試運行

java.lang.IllegalMonitorStateException 
    at java.lang.Object.wait(Native Method) 
    at java.lang.Object.wait(Object.java:485) 
    at TSend.GetMessage(TSend.java:39) 
    at TSend.run(TSend.java:78) 

回答

1

您是一些線程不擁有對被引用對象的監視器中調用

this.File_Message.wait(); 

。您在​​方法中執行此操作。在​​方法中,監視器是在this對象上獲取的。

這對我來說並不是顯而易見的,因爲你試圖在該對象上調用wait(),但是如果你想這樣做的話,你需要擁有它的顯示器。

檢查tutorial on synchronized methods和javadoc Object#wait()