views:

100

answers:

3

Hi everyone...

I've write a program with java that simulate production water with synchronization (Oxygen wait for Hydrogen to become available), but it's gives "Unexpected Operation Exeption" and did'nt work... Please help me...

there are my codes:

// class for thread Oxygen public class Thread_O implements Runnable {

Object object;

public Thread_O(Object o) {

    object = o;
}

public void run() {
    try {

        oxygen();

    } catch (InterruptedException ex) {
        Logger.getLogger(Thread_O.class.getName()).log(Level.SEVERE, null, ex);
    }
    throw new UnsupportedOperationException("Not supported yet.");
}

public void oxygen() throws InterruptedException {

    System.out.println("One O2 created...");

    synchronized (object) {

        object.wait();
        object.wait();
    }

    System.out.println("**** H2O created...");

}

}

// class for thread hydrogen public class Thread_H implements Runnable {

Object object;

public Thread_H(Object o) {

    object = o;
}

public void run() {
    try {

        Hydrogen();

    } catch (InterruptedException ex) {
        Logger.getLogger(Thread_H.class.getName()).log(Level.SEVERE, null, ex);
    }
    throw new UnsupportedOperationException("Not supported yet.");
}

public void Hydrogen() throws InterruptedException {

    System.out.println("One H2 created...");

    synchronized (object) {

        object.notifyAll();
    }
}

}

// in the main class we have:

Object object = new Object();

// in the button of Oxygen:

    Thread thread_O = new Thread(new Thread_O(object));
    thread_O.run();

// in the button of Hydrogen:

    Thread thread_H = new Thread(new Thread_H(object));
    thread_H.run();
+2  A: 

Your code is throwing the exception at the very last line of method run() in class Thread_O.

You need to delete this line.

Itay
+3  A: 

By the way, threads starts with method start() no run(). If you call run() then you perform the method but in the current thread no in the new one.

Gaim
I write Start() and no run() but I received the same exception...
Hero
I know, this is only tip. I think that your problem is in throwing an exception no in but after catch so you throw it always. But this has been written by others so I didn't want to repeat it.
Gaim
A: 

Your program is throwing the exception in the Thread_H and Thread_O run() methods. You've provided the implementation for the run() methods, so delete the lines that throw the exception. Delete these lines.

throw new UnsupportedOperationException("Not supported yet.");

@Gaim is correct you need to use start() to begin execution of the threads.

Wayne Young