生产者消费者设计模式

银行取钱问题:

银行卡类:

public class Card {
    private int money;
    private boolean choose;

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
	//存钱方法
    public synchronized void save(){
        while (choose){//choose初始值为true
            try {
                this.wait();//此时如果存钱线程抢到内存,则释放内存和锁,进入等待状态。
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        money+=1000;
        System.out.println(Thread.currentThread().getName()+"存了1000元,当前余额"+this.money);
        choose=true;//更改标记为true,使之可以进入取钱方法
        this.notifyAll();//唤醒所有等待的线程,如果写notify,因为是随机唤醒,所以在执行n次后,会因为存钱或者取钱线程全部等待而进入死锁
    }
    //取钱方法
    public synchronized void sub(){
        while (!choose){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        money-=1000;
        System.out.println(Thread.currentThread().getName()+"取了1000元,当前余额"+this.money);
        choose=false;
        this.notifyAll();
    }
}

存钱类:

public class Add implements Runnable {//实现runnable接口继承run方法
    Card card;  //实例化card对象

    public Add(Card card) {
        this.card = card;
    }

    @Override
    public void run() {
        for (int i=0;i<10;i++) {//存取十次
            card.save();
        }
    }
}

取钱类:

public class Sub implements Runnable{
    Card card;  
    public Sub(Card card) {
        this.card = card;
    }

    @Override
    public void run() {
        for (int i=0;i<10;i++) {
            card.sub();
        }
    }
}

测试类:

public class Test {
    public static void main(String[] args) throws Exception{
        Card card =new Card();
        Add add =new Add(card);
        Sub sub = new Sub(card);//传入同一个card对象,存取在一个数据中
        Thread t1=new Thread(add, "zhangsan");
        Thread t2 = new Thread(sub, "lisi");
        t1.start();
        t2.start();
    }
}

生产者消费者设计模式保证了一产一消的结构,两个线程一一对应,不会出现多个线程同时取导致的数据错误问题,但是设置过多会影响网络传输速度,一般用在传输比较重要的信息上。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值