开发者

help in synchronized method in java

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();

开发者_Python百科    } 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();


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.


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

You need to delete this line.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜