1、生產者僅僅在倉儲未滿時候生產,倉滿則停止生產。
2、消費者僅僅在倉儲有產品時候才能消費,倉空則等待。
3、當消費者發現倉儲沒產品可消費時候會通知生產者生產。
4、生產者在生產出可消費產品時候,應該通知等待的消費者去消費
使用object的wait()/notify()方法
1.wait():當快取區已滿/已空時,生產者/消費者執行緒自己停止自己的執行,放棄鎖,使自己處於等待狀態,讓其他程序執行。
2.notify():放生產者/消費者向快取區放入/取出乙個產品時,向其等待的執行緒發出可執行的通知,同時放棄鎖,使自己處於等待狀態。
這個模式有兩種寫法:管程法 和 訊號燈法
附上**(管程法):
package nsu.edu.one;
/** * 生產者消費者模式--->管程法
* 模擬生產饅頭和消費饅頭
*/public class main
}//生產者
class producer_one extends thread
public void run() catch (interruptedexception e)
system.out.println("生產第"+i+"個饅頭");
buffer.push(new bread(i)); }}
}//消費者
class consumer_one extends thread
public void run() catch (interruptedexception e)
system.out.println("消費第"+buffer.consumption().id+"個饅頭");
buffer.consumption();}}
}//緩衝區
class buffer catch (interruptedexception e)
} //有資料可以消費
count--;
bread bread = warehouse[count];
//消費完了 通知生產者可以生產
this.notifyall();
return bread;
} public synchronized void push(bread bread) catch (interruptedexception e)
} //有空間可以生產
warehouse[count] = bread;
count++;
this.notifyall(); }}
//饅頭
class bread
}
附上**(訊號燈法):
/**
* 生產者消費者模式--->訊號燈法
* */
public class main
}//生產者
class producer_one extends thread
public void run() }}
//消費者
class consumer_one extends thread
public void run() }}
//訊號燈
class signal catch (interruptedexception e)
} //開始生產
system.out.println("生產");
flug=!flug; //生產完了,新號燈轉變狀態
this.notifyall();
} //消費
public synchronized void pop() catch (interruptedexception e)
} //消費
system.out.println("消費");
flug=!flug; //生產完了,新號燈轉變狀態
this.notifyall();
}}
努力呀! java多執行緒(生產者 消費者)
if isempty 當生產者生產出來商品需要喚醒消費者消費,可進行如下控制 vector.vector.notify 喚醒消費方法還用到了同步的方法,具體語法如下 synchronized vector.vector 程式源 如下 public class thread01 public stat...
java多執行緒實現生產者消費者模式
package cn.learn.test public class waitnotifytest catch interruptedexception e inte ce lock class eatthread implements runnable override public void r...
Java多執行緒之消費者生產者模式
這個例項應該是學習執行緒的乙個經典例子,生產者和消費者模式。寫的很好,詳細請看內容。author shijin 生產者與消費者模型中,要保證以下幾點 1 同一時間內只能有乙個生產者生產 生產方法加鎖sychronized 2 同一時間內只能有乙個消費者消費 消費方法加鎖sychronized 3 生...