生產消費線程型是理解多線程的一個好例子,實際上,準確說應該是“生產者-消費者-倉儲”模型,離開了倉儲,生產者消費者模型就顯得沒有說服力了。
對於此模型,應該明確一下幾點:
1、生產者僅僅在倉儲未滿時候生產,倉滿則停止生產。
2、消費者僅僅在倉儲有產品時候才能消費,倉空則等待。
3、當消費者發現倉儲沒產品可消費時候會通知生產者生產。
4、生產者在生產出可消費產品時候,應該通知等待的消費者去消費。
代碼:
1生產線程類:
Code:
- import java.util.List;
-
- public class Product implements Runnable {
- private List container = null;
- private int count;
-
- public Product(List lst) {
- this.container = lst;
- }
-
- public void run() {
- while (true) {
- synchronized (container) {
- if (container.size() >= MultiThread.MAX) {//如果大於設定的MAX庫存,生產者就wait等待
- try {
- container.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- container.add(new Object());
- container.notify();//notify叫醒其他在container上的線程(消費者)
- System.out.println("我生產了" + (++count) + "個");
-
- }
- }
- }
- }
--
2消費線程:
Code:
- import java.util.List;
-
- public class Consume implements Runnable {
- private List container = null;
- private int count;
-
- public Consume(List lst) {
- this.container = lst;
- }
-
- public void run() {
- while (true) {
- synchronized (container) {
- if (container.size() == 0) {//如果容器已經空了,消費者wait等待(生產者)
- try {
- container.wait();// 放棄鎖
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- container.remove(0);
- container.notify();//叫醒生產者
- System.out.println("我吃了" + (++count) + "個");
- }
- }
- }
- }
--
3.運行測試:
Code:
- import java.util.ArrayList;
- import java.util.List;
-
- public class MultiThread {
- private List container = new ArrayList();
- public final static int MAX = 3;//最大庫存
-
- public static void main(String args[]) {
- MultiThread m = new MultiThread();
- new Thread(new Consume(m.getContainer())).start();
- new Thread(new Product(m.getContainer())).start();
- }
-
- public List getContainer() {
- return container;
- }
-
- public void setContainer(List container) {
- this.container = container;
- }
- }
本例中當發現不能滿足生產或者消費條件的時候,調用對象的wait方法,wait方法的作用是釋放當前線程的所獲得的鎖,並調用對象的notify() 方法,通知(喚醒)該對象上其他等待線程,使得其繼續執行。這樣,整個生產者、消費者線程得以正確的協作執行。
notify() 方法,起到的是一個通知作用,不釋放鎖,也不擷取鎖。