Java堆空间生产者消费者

时间:2015-08-22 02:10:32

标签: java multithreading producer-consumer

我正在学习使用wait和notify方法实现生产者消费者问题。我使用链接列表,并为列表设置限制为20个项目。以下是代码:

import java.util.LinkedList;
import java.util.Random;

public class ProducerConsumer {

    private static final int MAX_SIZE = 10;
    LinkedList<Integer> queue = new LinkedList<Integer>();

    public static void main(String[] args) {
        ProducerConsumer pc = new ProducerConsumer();

        Thread prod = new Thread(new Producer(pc.queue));
        Thread cons = new Thread(new Consumer(pc.queue));

        prod.start();
        cons.start();
    }

}

class Producer implements Runnable {

    // Produce until queue is full.
    private LinkedList sharedQueue;

    Producer(LinkedList sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    public void run() {

        while (true) {
            synchronized (sharedQueue) {

                System.out.println("size : " + sharedQueue.size());
                while (sharedQueue.size() >= 20) {
                    try {
                        sharedQueue.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                Random random = new Random();
                int i = random.nextInt();
                System.out.println("Produced: " + i);
                sharedQueue.add(i);
                sharedQueue.notifyAll();
            }
        }
    }
}

class Consumer implements Runnable {

    // Produce until queue is full.
    private LinkedList sharedQueue;

    Consumer(LinkedList sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    public void run() {

        while (true) {
            synchronized (sharedQueue) {
                while (sharedQueue.isEmpty()) {
                    try {
                        sharedQueue.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                System.out.println("Element consumed : " + sharedQueue.removeFirst());
                sharedQueue.notifyAll();
            }
        }
    }
}

很明显,当队列大小大于或等于20时(尽管我怀疑甚至需要更大的条件),我让生产者线程等待。此外,我在制作时打印了列表的大小,并且我从未在日志中获得大于20的大小。但是,当我运行上面的程序时,我得到Java堆空间错误。如何修改上述程序可以获得任何帮助。

0 个答案:

没有答案