【发布时间】:2023-03-08 02:38:01
【问题描述】:
我用 java 编写了一个程序来模拟生产水的同步(氧气等待氢气可用),但它给出了“意外操作异常”并且没有工作...... 请帮帮我...
有我的代码:
// 线程 Oxygen 的类 公共类 Thread_O 实现 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...");
}
}
// 线程氢类 公共类 Thread_H 实现 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();
}
}
}
//在我们的主类中:
Object object = new Object();
//在氧气按钮中:
Thread thread_O = new Thread(new Thread_O(object));
thread_O.run();
//在Hydrogen的按钮中:
Thread thread_H = new Thread(new Thread_H(object));
thread_H.run();
【问题讨论】:
-
哇,三个重复的线程,一个被关闭了,因为它与另一个重复
标签: java multithreading concurrency