编制生产者一消费者算法模拟一个生产吉、一个消费者;共享一个缓冲池的情开。1实现对经典的生产吉一消费吉问题的模拟以便更好的理解此经典进程同步问题。生产者一消费者问题是典型的 Pv操作问题假设系統中有一个比较大的缓冲池生产者的任务是只要缓冲池末满就可以将生产出的产品放入其中而消费者的任务是只要缓史池未空就可以以缓冲池中皇走产品。缓冲池被占用时任何进程都不能访问。2、每一个生产吉都要把自己生产的产品放入

public class ProducerConsumer { static int bufferSize = 5; static int[] buffer = new int[bufferSize]; static int in = 0; static int out = 0; static int count = 0;

public static void main(String[] args) {
    Thread producer = new Thread(new Producer());
    Thread consumer = new Thread(new Consumer());
    producer.start();
    consumer.start();
}

static class Producer implements Runnable {
    public void run() {
        while (true) {
            synchronized (buffer) {
                while (count == bufferSize) {  // 缓冲池满了,等待消费者消费
                    try {
                        buffer.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                buffer[in] = (int) (Math.random() * 10);
                System.out.println("Produced item: " + buffer[in]);
                in = (in + 1) % bufferSize;
                count++;
                buffer.notifyAll();  // 通知消费者
            }
        }
    }
}

static class Consumer implements Runnable {
    public void run() {
        while (true) {
            synchronized (buffer) {
                while (count == 0) {  // 缓冲池空了,等待生产者生产
                    try {
                        buffer.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                int item = buffer[out];
                System.out.println("Consumed item: " + item);
                out = (out + 1) % bufferSize;
                count--;
                buffer.notifyAll();  // 通知生产者
            }
        }
    }
}

}

标签: 教育


原文地址: https://gggwd.com/t/topic/b4if 著作权归作者所有。请勿转载和采集!