jave线程间通信

买卖商品来介绍:卖家首先要进货上架商品;等待客人来买;客人把商品买完了,需要等待卖家进货上架商品;如此循环

首先建一个代表商品的对象


public class CommondityEntity {

    private int num = 0;
    private String name = "杯子";

    public int getNum() {
        return num;
    }


    public synchronized void add(){
        ++num;
    }
    public synchronized void reduce(){
        --num;
    }
}

代表商人的线程类

public class Merch extends Thread {


    private CommondityEntity ce;

    public Merch(CommondityEntity ce) {
        this.ce = ce;
    }

    @Override
    public void run() {
        synchronized (ce) {
            try {
                super.run();
                while (true) {

                    if (ce.getNum() == 1) {
                        //进货了,库存已满,等待卖出
                        ce.wait();
                    }
                    if (ce.getNum() == 0) {
                        ce.add();
                        //通知买家进货了
                        ce.notify();
                        System.out.println("商家进货了!现产品库存为" + ce.getNum() + " 等待卖出!!!");
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

代表买家的类

public class Client extends Thread {


    private CommondityEntity ce;

    public Client(CommondityEntity ce) {
        this.ce = ce;
    }


    @Override
    public void run() {
        synchronized (ce) {
            try {

                super.run();
                while (true) {
                    if (ce.getNum() == 0) {
                        //卖家的货物已经卖光,等待商家进货才能继续购买
                        ce.wait();
                    }
                    if (ce.getNum() == 1) {
                        ce.reduce();
                        //通知卖家没货了,需要进货  -- 唤醒线程
                        ce.notifyAll();
                        System.out.println(this.getName()+" 购买了一件商品!现产品库存为" + ce.getNum() + " 等待商家进货");
                        Thread.sleep(1000);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

 

测试:

public static void main(String[] args) {
        CommondityEntity ce = new CommondityEntity();
        Thread t = new Client(ce);
        t.setName("买家1");
        Thread t3 = new Client(ce);
        t3.setName("买家2");
        Thread t2 = new Merch(ce);
        t.start();
        t2.start();
        t3.start();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值