实现生产者消费者问题

package com.bzw.multithreaded;

import java.util.LinkedList;
import java.util.Queue;

public class ProducedCustom {

    public static void main(String[] args) {

        Produce produce = new Produce();

        Producer producer = new Producer(produce);
        Customer customer = new Customer(produce);
        producer.start();
        customer.start();


    }


}

class Produce{

    private final static int size = 20;
    Queue<Integer> queue = new LinkedList<>();
    public synchronized void put(int i){
        if (queue.size() >= size ){
            System.out.println("仓库已满,停止生产");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "生产者生产了第" + i + "件商品");
        queue.add(i);
        notify();
    }

    public synchronized int get(){
        if (queue.isEmpty()){
            System.out.println("库存为空,停止销售");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int val = queue.poll();
        System.out.println(Thread.currentThread().getName() + "消费者购买了第" + val + "件商品");
        notify();
        return val;
    }

}

class Producer extends Thread{

    private Produce produce;

    public Producer(Produce produce){
        this.produce = produce;
    }
    public void run(){
        for (int i=0;i<=40;i++){
            produce.put(i);
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
    }
}

class Customer extends Thread{
    private Produce produce;

    public Customer(Produce produce){
        this.produce = produce;
    }
    public void run(){
        while (true){
            produce.get();
        }

    }
}

  这里用来一个Produce类表示仓库,用队列来存储数据,生产者和消费者都是通过仓库间接通信。当仓库满时,让生产者wait();当仓库空时,让消费者wait()。在消费者和生产者中的run方法中都是调用仓库中的方法,实现数据共享。

posted @ 2020-12-20 17:35  晚安1024  阅读(90)  评论(0)    收藏  举报