生产者消费者问题(java)

代码可直接复制运行!

public class Main {
    public static void main(String[] args) {
        LinkedList buffer = new LinkedList<>();//共享缓冲区
        int capacity = 10;//缓冲区大小
        Producer producer = new Producer(buffer, 10, 30);
        Consumer consumer = new Consumer(buffer, 10);
        Thread producerThread = new Thread(producer);
        Thread consumerThread = new Thread(consumer);
        producerThread.start();
        consumerThread.start();
    }
}

class Producer implements Runnable {
    LinkedList buffer = new LinkedList<>();
    int capacity;//缓冲区大小
    int num;//生产的个数

    Producer(LinkedList buffer, int capacity, int num) {
        this.capacity = capacity;
        this.num = num;
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for(int i = 0; i < num; i++) {
            try {
                synchronized (buffer) {
                    //buffer缓存已满,释放锁
                    while (buffer.size() == capacity) {
                        buffer.wait();
                    }

                    buffer.addLast(i);
                    System.out.println("生产了" + i);
                    buffer.notifyAll();//唤醒消费线程
                }
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable {
    LinkedList buffer = new LinkedList<>();
    int capacity;

    Consumer(LinkedList buffer, int capacity) {
        this.buffer = buffer;
        this.capacity = capacity;
    }

    @Override
    public void run() {
        while(true) {
            try {
                synchronized (buffer) {
                    //buffer缓存是空的,释放锁
                    if (buffer.size() == 0) {
                        buffer.wait();
                    }

                    int i = buffer.removeFirst();
                    System.out.println("消费了" + i);
                    buffer.notifyAll();//唤醒生产者线程
                }
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

参考博客:Java实现生产者消费者问题_用java语言模仿“生产者—消费者问题”-CSDN博客

你可能感兴趣的:(机试题,java,开发语言,算法)