N
noident
Greetings!
I am trying to make a simple thread/conncurrency example work.
What I am trying to do in the following simple code example is:
1. Start a thread
2. Make the started thread become another object's (String s) monitor
by executing a synchronized() statement
3. Call wait().
But it fails with an IllegalMonitorStateException.
If I understand the documentation correctly, I am under impression that
if the code within the synchronized() {} block is executing, the thread
is already the monitor of the object it's synchronizing on, but that
seems not to be the case
The following simple program fails, and I can't figure out what's
wrong. I must be missing something simple.
import java.util.*;
public class Foo extends Thread
{
private String s;
public Foo(String ss) { s = ss; }
public void run()
{
synchronized(s) // changing this line to 'synchronized(this)' fixes
the problem
{
try
{
wait();
}
catch(InterruptedException e)
{
System.err.println(e);
System.exit(1);
}
}
}
public static void main(String[] args)
{
new Foo("abc").start();
}
}
Running the above produces this:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:474)
at Foo.run(Foo.java:14)
my java version is:
java version "1.5.0_06"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode)
Any suggestions will be very much appreciated.
I am trying to make a simple thread/conncurrency example work.
What I am trying to do in the following simple code example is:
1. Start a thread
2. Make the started thread become another object's (String s) monitor
by executing a synchronized() statement
3. Call wait().
But it fails with an IllegalMonitorStateException.
If I understand the documentation correctly, I am under impression that
if the code within the synchronized() {} block is executing, the thread
is already the monitor of the object it's synchronizing on, but that
seems not to be the case
The following simple program fails, and I can't figure out what's
wrong. I must be missing something simple.
import java.util.*;
public class Foo extends Thread
{
private String s;
public Foo(String ss) { s = ss; }
public void run()
{
synchronized(s) // changing this line to 'synchronized(this)' fixes
the problem
{
try
{
wait();
}
catch(InterruptedException e)
{
System.err.println(e);
System.exit(1);
}
}
}
public static void main(String[] args)
{
new Foo("abc").start();
}
}
Running the above produces this:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:474)
at Foo.run(Foo.java:14)
my java version is:
java version "1.5.0_06"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode)
Any suggestions will be very much appreciated.