java 生产者消费者问题-多线程与死锁

本文通过一个具体的生产者消费者模式实例,展示了如何使用Java实现线程间的同步和通信。该示例中,生产者负责创建带有唯一ID的项,而消费者则移除这些项。通过synchronized关键字和wait/notify机制确保了线程的安全执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

代码 示例 

 

//想象这是馒头,每个馒头有自己的id

class Item{

    private int id=0;


    public Item(int id) {
        this.id=id;
    }
   
    public int getID(){
        return id+1;
    }
}

 

 

//想象这是装馒头的框子

 

class Stack{

//最多装5个  

    Item []arr=new Item[5];

    int index=0;  //记录装了几个

//添加与移除方法:都得上锁
 
    public synchronized void add(Item it){
        while(index==5){
            try {
                wait();   //如果满了就不能装了,线程wait
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        arr[index]=it;
        index++;

        notify();    //别忘了唤醒移除线程

    } 
 
    public synchronized Item remove(){
        while(index==0){
            try {
                this.wait();    没了就不能去除了,wait
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
 
        notify();   //唤醒添加线程。刚才不是wait了吗,然后进行一些操作:
        index--;
        Item it=arr[index];
        arr[index]=null;
 
        return it;
 
    }
}



生产馒头的:生产者

class Produce implements Runnable{
  Stack s=null;
    public Produce(Stack s){
        this.s=s;

    }

//生产20个就算了吧,不然循环起来没完了
 
    public void run(){
        for(int i=0;i<20;i++){
            s.add(new Item(i));
            System.out.println("Pro: "+(i+1));
            try {
                Thread.sleep(400);  睡一会是为了更好的观察输出,你设成0的话 再看就看不出来运行过程了
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

} 

 

消费者


class Consume implements Runnable{
    Stack s=null;
    public Consume(Stack s){
        this.s=s;
    }
    public void run(){
        for(int i=0;i<20;i++){
            System.out.println("Remove: "+ s.remove().getID());
            try {
                Thread.sleep(400);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

测试

public class TestPandC{
    public static void main(String[] args){
        Stack s=new Stack();
        new Thread(new Produce(s)).start();
        new Thread(new Consume(s)).start();
    }

}

运行一下看看 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值