生产消费者问题代码

本文探讨了并发编程中的苹果箱生产者消费者模式,通过使用Java的线程和同步机制,实现了一个简单的多线程应用,展示了如何在多线程环境下安全地进行资源的存取操作。
public class Test {

    
    public static void main(String[] args) {
        AppleBox ab=new AppleBox();
        
        Producer p=new Producer(ab);
        Consumer c=new Consumer(ab);
        Consumer cd=new Consumer(ab);
        
        new Thread(p).start();
        new Thread(c).start();
        
        new Thread(cd).start();

    }

}

class Apple{
    int id;
    Apple(int id){
        this.id=id;
    }
    public String toString(){
        return "apple "+id;
    }
}

class AppleBox{
    int index=0;
    Apple[] apples=new Apple[5];
    
    
    public synchronized void deposite(Apple apple){
        while(index==apples.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
    //    System.out.println(Thread.currentThread().getName()+"开始放入苹果了");
        apples[index]=apple;
        index++;        
    }
    
    public synchronized Apple withdraw(){
        while(index==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        //System.out.println(Thread.currentThread().getName()+"开始取出苹果了");
        index--;
        return apples[index];
    }
    
}

class Producer implements Runnable{
    AppleBox ab=null;
    Producer(AppleBox ab){
        this.ab=ab;
    }
    @Override
    public void run() {
        for(int i=0;i<20;i++){
            Apple a=new Apple(i);
            ab.deposite(new Apple(i));
            System.out.println(Thread.currentThread().getName()+"生产了:"+a);
            try {
                Thread.sleep((int)(Math.random()*1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
}

class Consumer implements Runnable{
    AppleBox ab=null;
    Consumer(AppleBox ab){
        this.ab=ab;
    }
    @Override
    public void run() {
        for(int i=0;i<20;i++){
            Apple a=ab.withdraw();
            System.out.println(Thread.currentThread().getName()+"消费了"+a);
            try {
                Thread.sleep((int)(Math.random()*1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值