I’m trying to write a code which wants to make a write thread. When I want to run it, I got this exception. Each post that I saw about this topic didn’t have the code same as mine. So can any one help me about my problem?
java.lang.IllegalMonitorStateException
The stacktrace is as below:
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at prj.McWThread.ReadPacket(McWThread.java:40)
at prj.McWThread.run(McWThread.java:73)
The part of code that makes this exception is :
public void run()
{
try{
while (true)
{
this.MyPkt = ReadPacket();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(MyPkt);
}
}
}
Readpacket method:
public MyPacket ReadPacket()
{
MyPacket m = new MyPacket();
System.out.println("ReadPacket");
try {
while (Buff.isEmpty()) {
wait();
}
}
catch (InterruptedException ie) {
ie.printStackTrace();
}
if (! Buff.isEmpty()) {
m = (MyPacket) Buff.remove(0);
return m;
} else {
return m;
}
}
You need to
synchonizeyour call to wait in your code. Two Options:Declare your method as syncronised
public syncronized MyPacket ReadPacket()
use
synchronized(this)before your call towait.The first one may not be advisable depending on your design and the work other threads need to carry out, if any.
For the second option, again, you need to be sure if you would want to use
thisas your monitor. You can create aLockand use that instead.