內容概要:
1. 執行緒間通訊的示例**
2. 安全問題的解決
3. 等待喚醒機制
4. **優化
5. 生產者消費者例子
6. 生產者消費者例子**優化(jdk5.0公升級版)
可以發現,執行輸出出現了錯誤的情況。
更改後**
執行發現,修改後的**輸出無錯誤,但是出現了大片連續的相同輸出。
執行輸出如圖,**加入等待喚醒機制後,實現了執行緒交替執行的目的。
class
res catch (exception e){}
this.name = name;
this.*** = ***;
flag = true;
this.notify();
}public synchronized void out()//提供資料訪問方法
catch (exception e){}
system.out.println(name+"++++++"+***);
flag = false;
this.notify();
}}class
input
implements
runnable
public
void run()
}}class
output
implements
runnable
public
void run()
}}class
iodemo1
}
當有多個生產者,多個消費者時,必須迴圈判斷標記,避免生產多個,消費乙個,或者生產乙個,消費多次等情況出現
class
resource
catch (exception e)
}this.name = name+" "+count++;
system.out.println(thread.currentthread().getname()+"
flag = true;
notifyall();
}public synchronized void get()
catch (exception e)
}system.out.println(thread.currentthread().getname()+"------>消費者-"+name);
flag = false;
notifyall();
}}class
producer
implements
runnable
public
void run()
}}class
consumer
implements
runnable
public
void run()
}}class
producerconsumerdemo
}
Java執行緒學習筆記(8) 執行緒間通訊
多個執行緒併發執行時,在預設情況下cpu是隨機切換執行緒的,如果我們希望他們有規律的執行,就可以使用通訊,例如每個執行緒執行一次列印 package threadtest public class demo12 catch interruptedexception e start new threa...
java執行緒間通訊
執行緒間通訊 其實就是多個執行緒在操作同乙個資源,但是操作的動作不同 等待喚醒機制 wait notify notifyall 都是用在同步中,因為要對持有監視器 鎖 的執行緒操作。所以要是用在同步中,因為只有同步才具有鎖。等待喚醒必須是同乙個鎖,而鎖可以是任意物件,所以可以被任意物件呼叫的方法定義...
Java執行緒間通訊
要求用子執行緒和主線程實現 子執行緒輸出20次,主線程輸出50次,然後再子執行緒輸出20次,主線程輸出50次,如此迴圈20次 1 建立乙個用於輸出的業務類 business class business catch interruptedexception e for int i 0 i 10 i ...