Simple(?) synchronized() block question



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.

.



Relevant Pages

  • Re: Simple(?) synchronized() block question
    ... implicitly on 'this' and synchronizing String s. ... Make the started thread become another object's (String s) monitor ... public static void main ... java version "1.5.0_06" ...
    (comp.lang.java.programmer)
  • Re: Question about sample Java application
    ... > private static String name; ... > public static void main{ ... In most of what I've been doing, when I have to do a Java ... application within that one .java file. ...
    (comp.lang.java.programmer)
  • Re: beginners question
    ... It must accept a String array as a parameter. ... public static void main ... When java tells you that it cannot find a method, ... requiring an applet viewer. ...
    (comp.lang.java)
  • JNI - unresolved _ZNSs4_Rep11_S_terminalE
    ... which (the main-driver) calls JAVA again to ... do the real work for processing the message. ... when starting the JAVA MainWrapper ... public static void main{ ...
    (comp.lang.java.programmer)
  • wrong ELF class: ELFCLASS64 when trying to link dynamic .so library from Java/JNA
    ... I have "installed" JNA in order to be able to access native calls from ... thus I would like a Java interface). ... public static void main(Stringargs) { ...
    (comp.unix.programmer)