我正在嘗試使用兩個不同的執行緒交替列印奇數和偶數,這些執行緒使用等待和通知以及使用鎖相互協調。
public class OddEvenPrinter {
private Object lock = new Object();
private boolean printFlag = false;
void printOdd() throws InterruptedException {
for(int i=1; i < 25; i=i 2){
synchronized (lock){
while(printFlag){
wait();
}
System.out.println(i "******** PRINT ODD ");
notifyAll();
}
}
}
void printEven() throws InterruptedException {
for(int i=0; i < 25; i=i 2){
synchronized (lock){
while(!printFlag){
wait();
}
System.out.println(i "******** PRINT EVEN ");
notifyAll();
}
}
}
我有一個驅動程式來驗證這一點。我們不能在 for 回圈中使用同步塊嗎?我收到非法監視器狀態例外。
public static void main(String[] args) throws InterruptedException {
OddEvenPrinter printer = new OddEvenPrinter();
Thread a = new Thread(new Runnable() {
@Override
public void run() {
try {
printer.printEven();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
Thread b = new Thread(new Runnable() {
@Override
public void run() {
try {
printer.printOdd();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
a.start();
b.start();
System.out.println("All DONE.....");
}
uj5u.com熱心網友回復:
問題:
您正在對lock物件進行同步,但呼叫wait()相當于this.wait().
請注意,它this代表的物件與所持有的物件不同lock,并且每個物件都有自己獨立的監視器。
您的每個執行緒在某些時候都會獲得 monitor oflock但隨后通過this.wait()它嘗試釋放 monitor of this。因為它從未獲得過該監視器IllegalMonitorStateException被拋出。
解決方案:
使用lock.wait()andlock.notifyAll()因為你的執行緒在lock.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491156.html
