自己在网上搜集了一些资料,然后又根据自己的理解写的,如果有问题,请指出,我将改正
- package cn.henu.sjg.producerAndConsumer;
- import java.util.LinkedList;
- import java.util.Scanner;
- /**
- * 生产者--消费者问题
- * @author Shang Jianguo
- * @2012-12-10 下午9:42:17
- */
- public class ProducerAndConsumer {
- private LinkedList<Object> container = new LinkedList<Object>(); // 作为缓冲区
- private int MAX = 10; // 缓冲区中商品的最多数量
- private boolean isEmpty = true;// 标志缓冲区是否为空
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入生产者数目:");
- int pnum = sc.nextInt();
- System.out.println("请输入消费者数目:");
- int cnum = sc.nextInt();
- ProducerAndConsumer pac = new ProducerAndConsumer();
- for(int i=0;i<pnum;i++){
- pac.new Producer("生产者" + i).start();
- }
- for(int i=0;i<cnum;i++){
- pac.new Consumer("消费者" + i).start();
- }
- }
- /**
- * 生产者类
- * @author Shang Jianguo
- * @2012-12-10 下午9:42:36
- */
- class Producer extends Thread {
- public Producer(String name) {
- super(name);
- }
- @Override
- public void run() {
- while (true) {
- synchronized (container) {
- if (isEmpty) {// 缓冲区为空并且没有生产
- if (MAX > container.size()) {// 向缓冲区中添加商品
- container.add("产品" + container.size());
- System.out.println(getName() + "生产了产品--" + container.getLast() );
- }
- isEmpty = false;
- container.notifyAll();
- } else {
- try {// 没有产品,线程等待
- container.notifyAll();
- container.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- }
- /**
- * 消费者类
- * @author shangjianguo
- */
- class Consumer extends Thread {
- public Consumer(String name) {
- super(name);
- }
- @Override
- public void run() {
- while (true) {
- synchronized (container) {
- try {
- container.wait(1000);
- } catch (InterruptedException e1) {
- e1.printStackTrace();
- }
- if (!isEmpty) {// 有商品
- Object good = container.removeLast();
- System.out.println(getName() + " 消费了商品:" + good);
- if (container.isEmpty()) {// 没有商品了
- isEmpty = true;
- }
- container.notifyAll();
- } else {
- System.out.println(getName() + ":没有商品了!");
- try {
- container.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- try {
- sleep(1000);
- } catch (InterruptedException e2) {
- e2.printStackTrace();
- }
- container.notifyAll();
- }
- }
- }
- }
- }
转载于:https://blog.51cto.com/shuaigee/1139370