Java实现生产者消费者问题

生产者-消费者(producer-consumer)问题,也称作有界缓冲区(bounded-buffer)问题,两个进程共享一个公共的固定大小的缓冲区。其中一个是生产者,用于将消息放入缓冲区;另外一个是消费者,用于从缓冲区中取出消息。问题出现在当缓冲区已经满了,而此时生产者还想向其中放入一个新的数据项的情形,其解决方法是让生产者此时进行休眠,等待消费者从缓冲区中取走了一个或者多个数据后再去唤醒它。同样地,当缓冲区已经空了,而消费者还想去取消息,此时也可以让消费者进行休眠,等待生产者放入一个或者多个数据时再唤醒它。

一,首先定义公共资源类,其中的变量number是保存的公共数据。并且定义两个方法,增加number的值和减少number的值。由于多线程的原因,必须加上synchronized关键字,注意while判断的条件。

package com.wjy.resources;

public class PublicResource {
private int number=0;
private static final int MAX_CAPACITY=3;
/**
 * increase resource
 */
    /** 
     * 增加公共资源 
     */  
    public synchronized void increace(String threadName) {  
        while (number >=MAX_CAPACITY) {  
            try {  
                wait();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
        number++;  
        System.out.println("Producer "+threadName+" product one:  "+number);  
        notify();  
    }  
  
    /** 
     * 减少公共资源 
     */  
    public synchronized void decreace(String threadName) {  
        while (number == 0) {  
            try {  
                wait();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
        number--;  
        System.out.println("Consumer "+threadName+" consume one:  "+number);  
        notify();  
    }  
}

二,分别定义生产者线程和消费者线程,并模拟多次生产和消费,即增加和减少公共资源的number值

package com.wjy.producer;

import com.wjy.resources.PublicResource;

public class ProducerThread implements Runnable{
    private PublicResource resource;  
    private String threadName;
    /**
      * 这样的构造函数可以使得生产者和消费者们共享公共资源,只要他们依赖的是同一个公共资源的对象。
      */
    public ProducerThread(PublicResource resource,String threadName) {  
        this.resource = resource;  
        this.threadName=threadName;
    }  
  
    @Override  
    public void run() {  
        /**
         * 生产者的生产次数
         */
        for (int i = 0; i < 5; i++) {  
            try {  
                Thread.sleep((long) (Math.random() * 1000));  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }
            resource.increace(threadName);
            
        }  
    }  
}
package com.wjy.consumer;

import com.wjy.resources.PublicResource;

public class ConsumerThread implements Runnable{
     private PublicResource resource;  
     private String threadName; 
     /**
      * 这样的构造函数可以使得生产者和消费者们共享公共资源,只要他们依赖的是同一个公共资源的对象。
      */
        public ConsumerThread(PublicResource resource,String threadName) {  
            this.resource = resource; 
            this.threadName=threadName;
        }  
      
        @Override  
        public void run() {  
            /**
             * 消费者的消费次数
             */
            for (int i = 0; i < 5; i++) {  
                try {  
                    Thread.sleep((long) (Math.random() * 1000));  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }
                resource.decreace(threadName);  
            }  
        }  
}

三,模拟多个生产者和消费者操作公共资源的情形,结果须保证是在允许的范围内。

package client;

import com.wjy.consumer.ConsumerThread;
import com.wjy.producer.ProducerThread;
import com.wjy.resources.PublicResource;
/**
 * This is an example that has three producers,two consumers.
 */
public class Client {
    public static void main(String[] args) {  
        PublicResource resource = new PublicResource();  
        
        Thread producerOne=new Thread(new ProducerThread(resource,"'生产者1号'")); 
        Thread producerTwo=new Thread(new ProducerThread(resource,"'生产者2号'"));  
        Thread producerThree=new Thread(new ProducerThread(resource,"'生产者3号'"));  
        
        Thread consumerOne=new Thread(new ConsumerThread(resource,"'消费者1号'"));
        Thread consumerTwo=new Thread(new ConsumerThread(resource,"'消费者2号'"));
        
        producerOne.start();
        consumerOne.start();
        consumerTwo.start();
        producerTwo.start();
        producerThree.start();
    }  
}
原文地址:https://www.cnblogs.com/wangjiyuan/p/multiThread.html