面试题:简单的实现一个生产者与消费者

思路:我们需要一个生产商品的线程类,以及一个消费商品的线程类,还有一个工具类,是编写生产以及消费的方法,供线程去调用

工具类:

/**
 * 工具类,生产与消费的方法
 */
class Cherk{
	// 商品库存
    private int product = 0;

	// 10个商品为最大库存量,为此生产出一个商品
    public synchronized void product() {
        while (product==10){
            System.out.println("库存已满");
            try {
            	// 当库存满的时候,线程调用wait方法,会释放锁
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        product++;
        System.out.println(Thread.currentThread().getName()+"生产了一个商品,当前库存为:"+product);
        System.out.println("仓库有货,数量为:"+product);
        // 唤醒其他等待的线程
        this.notifyAll();
    }

	// 消费方法,每次消费商品数量减一
    public synchronized void consumer()  {
        while (product<=0){
            System.out.println("没货了,心里没点数吗?");
            try {
            	// 当缺货了,就不让消费了,等待生产者生产商品
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        product--;
        System.out.println(Thread.currentThread().getName()+"消费了一个商品");
        // 唤醒等待的线程
        this.notifyAll();
    }
}

生产者:

class JymProducer implements Runnable{
	// 有一个Cherk类,供线程调用方法
    private Cherk cherk;

    public JymProducer(Cherk cherk) {
        this.cherk = cherk;
    }

	// 默认生产20次
    public void run() {
        for(int i = 0; i<20; i++){
            cherk.product();
        }
    }
}

消费者:

class JymConsumer implements Runnable{
	// 有一个Cherk类,供线程调用方法
    private Cherk cherk;

    public JymConsumer(Cherk cherk) {
        this.cherk = cherk;
    }
    
	// 默认生产20次
    public void run() {
        for(int i = 0; i<20; i++){
            cherk.consumer();
        }
    }
}

测试代码:

public class ProductAndConsumer {
    public static void main(String[] args) {
        Cherk cherk = new Cherk();
        new Thread(new JymProducer(cherk),"生产者A").start();
        new Thread(new JymProducer(cherk),"生产者B").start();
        new Thread(new JymConsumer(cherk),"消费者A").start();
        new Thread(new JymConsumer(cherk),"消费者B").start();
    }
}

学习年限不足,知识过浅,说的不对请见谅。

世界上有10种人,一种是懂二进制的,一种是不懂二进制的。

发布了71 篇原创文章 · 获赞 54 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/weixin_43326401/article/details/104107494