【问题标题】:IllegalMonitorStateException in thread线程中的 IllegalMonitorStateException
【发布时间】:2014-02-27 01:49:23
【问题描述】:

我想在线程中运行的 Vector 中使用同步

我尝试使用一种方法等待,另一种方法用于通知

我想从静态类调用通知方法 这是我的线程代码:

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

但我有这个例外,我尝试运行

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)

【问题讨论】:

    标签: java wait synchronized


    【解决方案1】:

    你在打电话

    this.File_Message.wait();
    

    在不拥有被引用对象上的监视器的某个线程中。您可以在 synchronized 方法中执行此操作。在synchronized 方法中,监视器是在this 对象上获取的。

    对我来说,您为什么要尝试在该对象上调用 wait() 并不明显,但如果您想这样做,您此时需要拥有它的监视器。

    查看tutorial on synchronized methodsObject#wait() 的javadoc。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      相关资源
      最近更新 更多