生产者使用者使用Java中的等待和通知功能

问题描述 投票:1回答:2

我已经使用Java中的等待和通知机制准备了生产者使用者。下面是代码:

class Producer implements Runnable {

    private int i = 0;
    private ArrayList<Integer> arrayList;
    private static final int MAX_SIZE = 5; 

    public Producer(ArrayList<Integer> arrayList) {
        this.arrayList = arrayList;
    }

    @Override
    public void run() {

        while(true) {
            try {
                produce(i++);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }           
        }
    }

    private synchronized void produce(int i) throws InterruptedException {

        while(arrayList.size() == MAX_SIZE) {

            System.out.println("The Queue is Full. Producer thread needs to wait.");

            wait();         
        }
        arrayList.add(i);
        System.out.println("Added Element: "+i);
        notifyAll();
        Thread.sleep(3000);         
    }
}

class Consumer implements Runnable {

    private ArrayList<Integer> arrayList;

    public Consumer(ArrayList<Integer> arrayList) {
        this.arrayList = arrayList;
    }   

    @Override
    public void run() {

        while(true) {   
            try {
                consume();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        }
    }

    private synchronized void consume() throws InterruptedException {

        while(arrayList.isEmpty()) {

            System.out.println("The Queue is empty. Consumer thread needs to wait.");

            wait();                 
        }
        int data = arrayList.remove(0);
        System.out.println("Removed Element: "+data);
        notifyAll();
        Thread.sleep(3000);
    }   
}

public class ProducerConsumerExample {

    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        Thread producer = new Thread(new Producer(arrayList), "Producer Thread");
        Thread consumer = new Thread(new Consumer(arrayList), "Consumer Thread");       
        producer.start();
        consumer.start();       
    }
}

下面是示例输出

The Queue is empty. Consumer thread needs to wait.
Added Element: 0
Added Element: 1
Added Element: 2
Added Element: 3
Added Element: 4
The Queue is Full. Producer thread needs to wait.

问题是使用者线程未收到通知或通知丢失。我曾尝试理解代码,但对我要去哪里出错却一无所知。

java wait producer-consumer notify
2个回答
2
投票

问题是使用者线程未收到通知或通知丢失


0
投票

生产者和消费者在其自己的实例上是同步的。但是,它应该在公共对象和我们必须调用等待和通知的同一对象上同步。我已修改您的代码以使其正常工作。请检查

© www.soinside.com 2019 - 2024. All rights reserved.