IllegalMonitorException using Semaphore and Monitor in Java
<p>I have a project for my "Operating Systems". I need to write 2 programs with java...</p>

<ol>
<li><p>write a program that produce Water with 2 method Oxygen and Hydrogen.
method Oxygen produce one Oxygen and method Hydrogen produce one hydrogen. when 2 Hydrogen and one Oxygen was existed H2O created. I must write this with  with Semaphores and threads.</p></li>
<li><p>Write the above problem with Monitors and Sychronize.</p></li>
</ol>

<p>I've writed some code for this but it gives illegal monitor exeption...
please help me to correct it...</p>

<p>This is my code:</p>

<pre><code>// class for implement Thread for oxygen
public class Thread_O implements Runnable {

    public void run() {

        thread t = new thread();

        try {
            t.oxygen();
        } catch (InterruptedException ex) {
            Logger logger = Logger.getLogger(Thread_O.class.getName());
            logger.log(Level.SEVERE, null, ex);
        }
    }
}


// class for implement Thread for Hydrogen
public class Thread_H implements Runnable {

    public void run() {

        thread t = new thread();

        try {
            t.Hydrogen();
        } catch (InterruptedException ex) {
            Logger logger = Logger.getLogger(Thread_H.class.getName());
            logger.log(Level.SEVERE, null, ex);
        }
    }
}

//class for method Oxygen and Hydrogen
public class thread {

    Semaphore O = new Semaphore(0, true);
    Semaphore H = new Semaphore(0, true);
    Semaphore H2O = new Semaphore(0, true);
    Semaphore safe = new Semaphore(1, true);

    public void oxygen() throws InterruptedException {

        safe.wait();

        H.wait();
        H.wait();

        H2O.release();
        H2O.release();

        Safe.release();
        //  System.out.println("O2...!");
    }

    public void Hydrogen() throws InterruptedException {

        H.release();
        H2O.wait();

        //   System.out.println("H2...!");
    }
}
</code></pre>

<p>and in action of Oxygen Button:</p>

<pre><code>    Thread th = new Thread(new Thread_O());
    th.start();
</code></pre>
