0

i want to use synchronized in Vector run in thread

i try tow methode one for wait and other for notfiy

i want to call the notify method from static class this my thread code :

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();
    }

and i try to do this :

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

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

but i have this excption wan i try to run

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 Answer 1

1

You are calling

this.File_Message.wait();

within some thread that does not own the monitor on the referenced object. You do this in a synchronized method. In a synchronized method, the monitor is acquired on this object.

It's not obvious to me why you are trying to call wait() on that object, but you'll need to own its monitor at that point if you want to do it.

Go through the tutorial on synchronized methods and the javadoc of Object#wait().

Not the answer you're looking for? Browse other questions tagged or ask your own question.