Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why this error  RSS feed

 
arun mahajan
Ranch Hand
Posts: 305
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am getting the error "java.lang.IllegalMonitorStateException: current thread not owner". can somebody help me to get rid of it?
regards,
Arun
Code:-
******
import java.io.*;
public class check
{
public static void main(String[] args)
{
check xx = new check();
a x = new a(xx);
b y = new b(xx);
try
{
y.start();
}catch(Exception e)
{
System.out.println("Error in start x: "+e);
}
try
{
x.start();
}catch(Exception e)
{
System.out.println("Error in start x: "+e);
}
}
}
class a extends Thread
{
public void run()
{
for(;
{
try
{
System.out.println("Into A");
wait(1*1000);
notifyAll();
}catch(Exception e)
{
System.out.println("Error in a: "+e);
}
}
}
}
class b extends Thread
{
public void run()
{
for(;
{
try
{
System.out.println("Into B");
wait(5*1000);
notifyAll();
}catch(Exception e)
{
System.out.println("Error in b: "+e);
}
}
}
}
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
first of all the a and the b constrcutors should look like this or ir wont compile:
a x = new a(); //(no xx inside)
b y = new b(); //(no xx inside)
next, when u use wait or notify calls they need to be in synchronized blocks or methods to ensure that the thread owns the objects lock.
so just add the synchronized keyword to each run method like this:
public synchronized void run()
 
arun mahajan
Ranch Hand
Posts: 305
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes it works with synchronized keyword.
Thanks a lot.
Arun
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!