线程经典,生产者与消费者问题

来源:互联网 发布:linux输入法下载 编辑:程序博客网 时间:2024/06/05 17:20

生产者与消费的问题,是线程编程的一个经典问题。生产者生产,消费者消费,当生产满的时候,生产者要停止生产,等待消费者消耗掉产品后再继续生产,消费者发现没有产品可以消费的时候,也必须等待,等待生产者生产出产品才能购买,看看下面的例子

package com.thread;import java.util.Random;/** * 生产者与消费者实例 *  * @author Administrator *  */public class ProducerAndConsumer {public static void main(String[] args) {ProductHeap ph = new ProductHeap();Random random = new Random();Producer p = new Producer(ph, random);Consumer c = new Consumer(ph, random);new Thread(p).start();new Thread(p).start();new Thread(c).start();}}/** * 产品类 *  * @author Administrator *  */class Product {public int id;public Product(int id) {this.id = id;}@Overridepublic String toString() {return "产品:" + id;}}/** * 产品堆 *  * @author Administrator *  */class ProductHeap {int index = 0;Product proArr[] = new Product[6];public synchronized void push(Product product) {// 如果产品满了while (index == proArr.length) {System.out.println("产品堆满了,消费者快买");try {// 当前线程等待this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}this.notifyAll();proArr[index] = product;index++;}public synchronized Product pop() {while (index == 0) {System.out.println("没产品了,快生产");try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}this.notifyAll();return proArr[--index];}}class Producer implements Runnable {private ProductHeap ph;private Random random;public Producer(ProductHeap ph, Random random) {this.ph = ph;this.random = random;}int i = 0;@Overridepublic void run() {while (true) {Product product = new Product(i++);ph.push(product);System.out.println("生产了:" + product);try {Thread.sleep((random.nextInt(3) * 500));} catch (Exception e) {}}}}class Consumer implements Runnable {private ProductHeap ph;private Random random;public Consumer(ProductHeap ph, Random random) {this.random = random;this.ph = ph;}@Overridepublic void run() {while (true) {Product p = ph.pop();System.out.println("消费了:" + p);try {Thread.sleep((random.nextInt(3) * 500));} catch (Exception e) {}}}}