本人采用java语言,用三种方式实现生产者——消费者的经典问题,至于生产者和消费的问题就不多说了,以下是第一种方式的具体代码:
- <span style="font-family:Arial;">
- /**
- * 消费者:生产者:生产者和消费者共用一个仓库
- */
- public class Consumer implements Runnable {
- private Storage storage;
- public Consumer(Storage storage) {
- this.storage = storage;
- }
- // 消费
- public void cunsume() {
- while (true) {
- storage.get();
- try {
- Thread.sleep(1500); // 每消费完一件产品,休息1.5秒
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
- @Override
- public void run() {
- this.cunsume();
- }
- }
- </span>
- <span style="font-family:Arial;">
- /**
- * 生产者:生产者和消费者共用一个仓库
- */
- public class Producer implements Runnable {
- private Storage storage;
- public Producer(Storage storage){
- this.storage = storage;
- }
- @Override
- public void run(){
- this.produce();
- }
- // 生产
- public void produce(){
- while(true){
- storage.put();
- try {
- Thread.sleep(1000); // 每生产完一件产品,休息1秒
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- }
- }
- </span>
- <span style="font-family:Arial;">
- /**
- * 仓库:
- * 先生产的先消费:使用队列的方式实现
- */
- public class Storage {
- public static final int MAX_SIZE = 100; // 仓库的最大货存
- // 容器,为了使用方便,没有面向接口编程,使用LinkedList作为实现类
- private LinkedList<Object> container = new LinkedList<Object>();
- // 从仓库中存放一个产品:
- public synchronized void put(){
- try {
- while (container.size() == MAX_SIZE) {
- try {
- this.wait();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- System.out.println("put()等待结束,仓库现有数量为"+ container.size() +", 开始生产");
- container.addLast(new Object());
- } finally {
- this.notifyAll(); // 通知其他线程
- }
- }
- // 从仓库中取出一个产品:
- public synchronized Object get(){
- try {
- while (container.size() == 0) {
- try {
- this.wait();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- }
- System.out.println("get()等待结束,仓库现有数量为"+ container.size() +", 开始取出");
- return container.removeFirst();// 取出
- } finally {
- this.notifyAll(); // 通知其他线程
- }
- }
- }</span>
以下是测试代码:
- <span style="font-family:Arial;">
- public class Test {
- public static void main(String[] args) {
- Storage storage = new Storage();
- // 生产者和消费者两个线程类,用的必须是同一个仓库,即同一个仓库对象storage
- Consumer con = new Consumer(storage);
- Producer pro = new Producer(storage);
- new Thread(pro).start();
- new Thread(pro).start();
- new Thread(pro).start();
- new Thread(pro).start();
- // new Thread(con).start();
- // new Thread(con).start();
- // new Thread(con).start();
- // new Thread(con).start();
- new Thread(con).start();
- }
- }</span>
以下是测试代码结果:
get()等待结束,仓库现有数量为100, 开始取出
put()等待结束,仓库现有数量为99, 开始生产
get()等待结束,仓库现有数量为100, 开始取出
put()等待结束,仓库现有数量为99, 开始生产
get()等待结束,仓库现有数量为100, 开始取出
put()等待结束,仓库现有数量为99, 开始生产
get()等待结束,仓库现有数量为100, 开始取出
put()等待结束,仓库现有数量为99, 开始生产
get()等待结束,仓库现有数量为100, 开始取出
put()等待结束,仓库现有数量为99, 开始生产
get()等待结束,仓库现有数量为100, 开始取出
put()等待结束,仓库现有数量为99, 开始生产
get()等待结束,仓库现有数量为100, 开始取出
put()等待结束,仓库现有数量为99, 开始生产