多線程(十一)---等待喚醒機制原理
1.代碼演示
//多線程中通訊.多個線程都在處於同一資源,可是處理的任務卻不同
//生產者,生產一個麪包
//消費者,消費一個麪包.
class Res {
private int count = 1;// 麪包數量
private String name;
boolean flag;// 定義標記
// 提供了商品的賦值的方法
public synchronized void set(String name){
// 判斷標記 true 執行wait.等待,爲false.就生產
if(flag){
try {
wait();
} catch (InterruptedException e) {
}
}
this.name = name+"----"+count;
count++;
System.out.println(Thread.currentThread().getName()+"--生產者----"+this.name);
// 生產完畢,將標記改成true
flag = true;
// 喚醒消費者
this.notify();
}
// 提供了商品獲取的方法
public synchronized void get(){
if(!flag){
try {
wait();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName()+"---消費者---"+this.name);
// 將標記改成false
flag = false;
// 喚醒提供者
this.notify();
}
}
/**
* 消費者
*/
class Customer implements Runnable {
private Res r;
Customer(Res r){
this.r = r;
}
public void run(){
while (true) {
r.get();
}
}
}
/**
* 生產者
*/
class producer implements Runnable {
private Res r;
producer(Res r){
this.r = r;
}
public void run(){
while (true) {
r.set("麪包");
}
}
}
public class WaitAndNotifyDemo {
public static void main(String[] args) {
// 1.建立線程資源
Res r = new Res();
// 2.建立線程任務
producer p = new producer(r);
Customer c = new Customer(r);
// 3.執行線程
new Thread(p).start();
new Thread(c).start();
}
}
2.等待喚醒講解
wait():該方法能夠讓線程處於凍結狀態,並將線程臨時存儲到線程池中
notify():喚醒指定線程池中任意一個線程
notifyAll():喚醒指定線程池中全部線程
這些方法必須使用在同步中,若是不是在同步中會出現(IllegalMonitorStateException 異常),由於它們操做的同步鎖上的線程異常
在使用這些方法時,必須標識它們所屬於的鎖。標識方式就是 鎖對象.wait(),鎖對象.notify(),鎖對象.notifyAll()相同鎖的notify(),能夠獲取相同鎖的wait();