my dog learned polymorphism*
The moose likes Threads and Synchronization and the fly likes why this error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "why this error " Watch "why this error " New topic
Author

why this error

arun mahajan
Ranch Hand

Joined: Dec 07, 2001
Posts: 305
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

Joined: Jan 13, 2002
Posts: 732
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

Joined: Dec 07, 2001
Posts: 305
Yes it works with synchronized keyword.
Thanks a lot.
Arun
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why this error