Java多线程系列--“基础篇”11之 生产消费者问题

概要

本章,会对“生产/消费者问题”进行讨论。涉及到的内容包括:
1. 生产/消费者模型
2. 生产/消费者实现

转载请注明出处:http://www.cnblogs.com/skywang12345/p/3480016.html

 

1. 生产/消费者模型

生产/消费者问题是个非常典型的多线程问题,涉及到的对象包括“生产者”、“消费者”、“仓库”和“产品”。他们之间的关系如下:
(01) 生产者仅仅在仓储未满时候生产,仓满则停止生产。
(02) 消费者仅仅在仓储有产品时候才能消费,仓空则等待。
(03) 当消费者发现仓储没产品可消费时候会通知生产者生产。
(04) 生产者在生产出可消费产品时候,应该通知等待的消费者去消费。

 

2. 生产/消费者实现

下面通过wait()/notify()方式实现该模型(后面在学习了线程池相关内容之后,再通过其它方式实现生产/消费者模型)。源码如下:

1 // Demo1.java
  2 // 仓库
  3 class Depot {
  4     private int capacity;    // 仓库的容量
  5     private int size;        // 仓库的实际数量
  6 
  7     public Depot(int capacity) {
  8         this.capacity = capacity;
  9         this.size = 0;
 10     }
 11 
 12     public synchronized void produce(int val) {
 13         try {
 14              // left 表示“想要生产的数量”(有可能生产量太多,需多此生产)
 15             int left = val;
 16             while (left > 0) {
 17                 // 库存已满时,等待“消费者”消费产品。
 18                 while (size >= capacity)
 19                     wait();
 20                 // 获取“实际生产的数量”(即库存中新增的数量)
 21                 // 如果“库存”+“想要生产的数量”>“总的容量”,则“实际增量”=“总的容量”-“当前容量”。(此时填满仓库)
 22                 // 否则“实际增量”=“想要生产的数量”
 23                 int inc = (size+left)>capacity ? (capacity-size) : left;
 24                 size += inc;
 25                 left -= inc;
 26                 System.out.printf("%s produce(%3d) --> left=%3d, inc=%3d, size=%3d\n", 
 27                         Thread.currentThread().getName(), val, left, inc, size);
 28                 // 通知“消费者”可以消费了。
 29                 notifyAll();
 30             }
 31         } catch (InterruptedException e) {
 32         }
 33     } 
 34 
 35     public synchronized void consume(int val) {
 36         try {
 37             // left 表示“客户要消费数量”(有可能消费量太大,库存不够,需多此消费)
 38             int left = val;
 39             while (left > 0) {
 40                 // 库存为0时,等待“生产者”生产产品。
 41                 while (size <= 0)
 42                     wait();
 43                 // 获取“实际消费的数量”(即库存中实际减少的数量)
 44                 // 如果“库存”<“客户要消费的数量”,则“实际消费量”=“库存”;
 45                 // 否则,“实际消费量”=“客户要消费的数量”。
 46                 int dec = (size<left) ? size : left;
 47                 size -= dec;
 48                 left -= dec;
 49                 System.out.printf("%s consume(%3d) <-- left=%3d, dec=%3d, size=%3d\n", 
 50                         Thread.currentThread().getName(), val, left, dec, size);
 51                 notifyAll();
 52             }
 53         } catch (InterruptedException e) {
 54         }
 55     }
 56 
 57     public String toString() {
 58         return "capacity:"+capacity+", actual size:"+size;
 59     }
 60 } 
 61 
 62 // 生产者
 63 class Producer {
 64     private Depot depot;
 65     
 66     public Producer(Depot depot) {
 67         this.depot = depot;
 68     }
 69 
 70     // 消费产品:新建一个线程向仓库中生产产品。
 71     public void produce(final int val) {
 72         new Thread() {
 73             public void run() {
 74                 depot.produce(val);
 75             }
 76         }.start();
 77     }
 78 }
 79 
 80 // 消费者
 81 class Customer {
 82     private Depot depot;
 83     
 84     public Customer(Depot depot) {
 85         this.depot = depot;
 86     }
 87 
 88     // 消费产品:新建一个线程从仓库中消费产品。
 89     public void consume(final int val) {
 90         new Thread() {
 91             public void run() {
 92                 depot.consume(val);
 93             }
 94         }.start();
 95     }
 96 }
 97 
 98 public class Demo1 {  
 99     public static void main(String[] args) {  
100         Depot mDepot = new Depot(100);
101         Producer mPro = new Producer(mDepot);
102         Customer mCus = new Customer(mDepot);
103 
104         mPro.produce(60);
105         mPro.produce(120);
106         mCus.consume(90);
107         mCus.consume(150);
108         mPro.produce(110);
109     }
110 }

说明
(01) Producer是“生产者”类,它与“仓库(depot)”关联。当调用“生产者”的produce()方法时,它会新建一个线程并向“仓库”中生产产品。
(02) Customer是“消费者”类,它与“仓库(depot)”关联。当调用“消费者”的consume()方法时,它会新建一个线程并消费“仓库”中的产品。
(03) Depot是“仓库”类,仓库中记录“仓库的容量(capacity)”以及“仓库中当前产品数目(size)”。
        “仓库”类的生产方法produce()和消费方法consume()方法都是synchronized方法,进入synchronized方法体,意味着这个线程获取到了该“仓库”对象的同步锁。这也就是说,同一时间,生产者和消费者线程只能有一个能运行。通过同步锁,实现了对“残酷”的互斥访问。
       对于生产方法produce()而言:当仓库满时,生产者线程等待,需要等待消费者消费产品之后,生产线程才能生产;生产者线程生产完产品之后,会通过notifyAll()唤醒同步锁上的所有线程,包括“消费者线程”,即我们所说的“通知消费者进行消费”。
      对于消费方法consume()而言:当仓库为空时,消费者线程等待,需要等待生产者生产产品之后,消费者线程才能消费;消费者线程消费完产品之后,会通过notifyAll()唤醒同步锁上的所有线程,包括“生产者线程”,即我们所说的“通知生产者进行生产”。

(某一次)运行结果

Thread-0 produce( 60) --> left=  0, inc= 60, size= 60
Thread-4 produce(110) --> left= 70, inc= 40, size=100
Thread-2 consume( 90) <-- left=  0, dec= 90, size= 10
Thread-3 consume(150) <-- left=140, dec= 10, size=  0
Thread-1 produce(120) --> left= 20, inc=100, size=100
Thread-3 consume(150) <-- left= 40, dec=100, size=  0
Thread-4 produce(110) --> left=  0, inc= 70, size= 70
Thread-3 consume(150) <-- left=  0, dec= 40, size= 30
Thread-1 produce(120) --> left=  0, inc= 20, size= 50

 

代码修改:

=================分割线========================================

package com.hikvision.base.p11;

/**
 * @author zhangtuo
 * @Date 2017/3/1
 */
public class PThread_11 {

    private int num;//库存数量
    private int capacity;//最大容量


    public PThread_11(int capacity) {
        this.capacity = capacity;
        num = 0;//默认初始化库存数量为0
    }

    /**
     * 生产
     * @param val
     */
    public synchronized void produce(int val) {
        try {
            int left = val;
            if(val > 0) {
                while(num >= capacity) {
                    wait();//如果实际库存数量等于最大容量时,则等待消费。
                }
                int increase = (num + left) > capacity ? (capacity - num) : left;//实际生产数量
                num += increase;//库存数量变化
                left -= increase;//生产数量变化
                System.out.println("生产线程:" + Thread.currentThread().getName()
                        + ", 未生产数量:" + left + ", 实际生产数量:" + increase + ", 库存数量: " + num + "。");
                /**
                 * 只要是生产就应该唤醒消费线程来消费
                 */
                notifyAll();//唤醒所有线程
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 消费
     * @param val
     */
    public synchronized void consume(int val) {
        try {
            int right = val;//需要消费的数量
            if (val > 0) {
                while (num <= 0) {
                    wait();//如果实际库存数量为0,等待其他生产者进行生产。
                }
                int decrease = num < right ? num : right;//如果库存数量小于实际要消费的数量,则库存全部消费,否则消费实际。
                num -= decrease;//库存变化
                right -= decrease;//消费数量变化
                System.out.println("消费线程:" + Thread.currentThread().getName()
                        + ", 未消费数量:" + right + ", 实际消费数量:" + decrease + ", 库存数量: " + num + "。");
                /**
                 * 只要消费就要唤醒生产线程进行生产
                 */
                notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Demo {
    public static void main(String[] args) {
        PThread_11 p = new PThread_11(100);
        /**
         * 生产、消费线程针对p对象,synchronized获得的都是p的对象锁,生产者生产时,消费者不能参与被互斥。
         */
        Thread producer_1 = new Thread(new Runnable() {
            @Override
            public void run() {
                p.produce(60);
            }
        });
        Thread producer_2 = new Thread(new Runnable() {
            @Override
            public void run() {
                p.produce(120);
            }
        });
        Thread consumer_1 = new Thread(new Runnable() {
            @Override
            public void run() {
                p.consume(90);
            }
        });
        Thread consumer_2 = new Thread(new Runnable() {
            @Override
            public void run() {
                p.consume(150);
            }
        });
        Thread producer_3 = new Thread(new Runnable() {
            @Override
            public void run() {
                p.produce(110);
            }
        });
        producer_1.start();
        producer_2.start();
        producer_3.start();
        consumer_1.start();
        consumer_2.start();
    }

}

 

转载于:https://my.oschina.net/zhangtuoDMU/blog/848454

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值