Java生产者-消费者问题 线程交互

该博客介绍了如何使用Java实现生产者-消费者问题的经典案例。通过Product类表示产品,ProductStack作为缓冲区,Producter和Consumer线程分别扮演生产者和消费者的角色,利用wait()和notifyAll()进行线程交互,确保数据同步。示例展示了如何在多线程环境中避免数据溢出和空指针异常,保证生产与消费的平衡。
摘要由CSDN通过智能技术生成

线程交互的应用

生产者-消费者问题是多线程数据同步的经典问题,请编程实现生产者、消费者和缓冲数据区域,并编写测试代码验证。

// 产品
public class Product {
    public int id;
    private String prodecuBy = "N/A";
    private String consumeBy = "N/A";

    // 产品ID,和生产者的名字
    public Product(int id, String prodecuBy) {
        this.id = id;
        this.prodecuBy = prodecuBy;
    }

    public String getProdecuBy() {
        return prodecuBy;
    }

    public void setProdecuBy(String prodecuBy) {
        this.prodecuBy = prodecuBy;
    }

    public String getConsumeBy() {
        return consumeBy;
    }

    public void setConsumeBy(String consumeBy) {
        this.consumeBy = consumeBy;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", prodecuBy='" + prodecuBy + '\'' +
                ", consumeBy='" + consumeBy + '\'' +
                '}';
    }
}
// 存储产品
public class ProductStack {
    public int index = 0;
    public Product[] products = new Product[5];
    //生产者放入
    public synchronized void push(Product product){
        // 等待,避免越界
        while (index >= products.length){
            System.out.println(product.getProdecuBy() + "is waiting!");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 唤醒
        System.out.println(product.getProdecuBy()+"send a notifyAll.");
        notifyAll();
        products[index] = product;
        index++;
        System.out.println(product.getProdecuBy()+"生产了"+product);
    }

    //消费者取出
    public synchronized Product pop(String consumerName){

        while (index == 0){
            System.out.println(consumerName + "is waiting!");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 唤醒等待的生产者
        System.out.println(consumerName+"send a notifyAll.");
        notifyAll();
        index--;
        Product product = products[index];
        System.out.println(product.getConsumeBy()+"生产了"+product);
        return product;
    }

}
// 消费者、生产者线程创建、运行线程
class Producter implements Runnable{
    private String name;
    private ProductStack productStack = null;

    public Producter(String name, ProductStack productStack) {
        this.name = name;
        this.productStack = productStack;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++){
            Product product = new Product(i, name);
            productStack.push(product);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable {
    private String name;
    private ProductStack productStack;

    public Consumer(String name, ProductStack productStack) {
        this.name = name;
        this.productStack = productStack;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            Product product = productStack.pop(name);

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


public class ProducerConsumer {
    public static void main(String[] args) {
        ProductStack productStack = new ProductStack();
        Producter producter = new Producter("生产者:A ", productStack);
        Consumer consumer = new Consumer("消费者:1", productStack);
        new Thread(producter).start();
        new Thread(consumer).start();
    }
}

结果截图:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码不会敲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值