我有一个“操作系统”项目。我需要用java编写两个程序..。
我已经为这个写了一些代码,但它给出了非法的监控程序.请帮我更正一下..。
这是我的密码:
// 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...!");
}
}氧气按钮的作用:
Thread th = new Thread(new Thread_O());
th.start();发布于 2009-12-30 06:54:25
我不会为您解码您的作业,但是当您试图对一个对象进行IllegalMonitorException而不是synchronized时,就会抛出一个synchronized。所以要等待一个名为list的对象
synchronized (list) {
try {
list.wait();
} catch(Throwable t) {
t.printStackTrace();
}
}发布于 2009-12-30 06:53:40
您必须了解生产者/消费者机制是如何工作的。
在这里,您将有一个消费者线程和两个生产者。
首先,你将有一条线产生氧气,另一条线产生氢。
那么,这些分子应该是“某处”的地方,好吗?“某样东西”是必须被监视和同步的东西。
所以应该是这样的:
class Water {
char [] waterMolecule = new char[3]; // <-- synchronize access to this
char hydrogen(){
return 'H';
}
char oxygen() {
return 'O';
}
void produce() {
Thread t = new Thread( new Runnable() {
synchronize( waterMolecule ) {
waterMolecule[0] = hydrogen();
}
}):
.... produce the others
}
void consume() {
synchronize watermolecule
if waterMolecule is complete
create water and clean out the molecule.
}
}这是基本的想法。
请记住,在前一个粒子被消耗之前,你将无法产生另一个粒子。
此外,您还必须始终在while循环中调用等待。
下面是如何对等待/同步进行编码。
下面是的一些生产者/消费者的样本。
发布于 2009-12-30 16:30:44
尽管您的作业已经到期,但我还是想提出CyclicBarrier作为这个场景的最佳解决方案。它允许不同线程(此处:您的分子生产者)进行某种会合,并触发在完成时执行额外的可运行(此处:创建h20)。
https://stackoverflow.com/questions/1978734
复制相似问题