[英]IllegalMonitorException using Semaphore and Monitor in Java
我有一個針對“操作系統”的項目。 我需要用Java編寫2個程序...
編寫一個程序用氧氣和氫氣兩種方法生產水。 方法氧氣產生一種氧氣,方法氫氣產生一種氫氣。 當存在2個氫和1個氧時會生成H2O。 我必須使用信號量和線程編寫此內容。
用Monitors和Sychronize編寫上述問題。
我已經為此編寫了一些代碼,但它給顯示器帶來了非法的麻煩……請幫助我糾正它……
這是我的代碼:
// 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();
我不會為您解碼作業,但是當您嘗試對對象進行wait()
而不進行synchronized
時,將拋出IllegalMonitorException。 因此,等待一個名為list
的對象:
synchronized (list) {
try {
list.wait();
} catch(Throwable t) {
t.printStackTrace();
}
}
您必須了解生產者/消費者機制的工作方式。
在這里,您將有一個消費者線程和兩個生產者。
首先,您將有一條產生氧氣的線,另一條產生氫氣。
那么,那些分子應該放在“某處”好嗎? “事物”是必須監視和同步的事物。
所以它應該是這樣的:
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循環中調用wait
這就是等待/同步的編碼方式。
這是一些生產者/消費者樣本。
盡管您的家庭作業已經到期,但我還是想提出CyclicBarrier作為這種情況的最佳解決方案。 它允許不同線程的某種集合(在這里:您的分子生產者),並在完成時觸發另一個可運行對象的執行(在這里:h20的創建)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.