栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java多线程练习-线程通信-取钱案例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java多线程练习-线程通信-取钱案例

java多线程练习-线程通信-取钱案例

案例需求:
      小明打算去提款机上取钱,发现卡上没有钱,这时候他告知妈妈去存钱,妈妈存了钱了,告知小明存好了可以取钱了。小明分多次取钱,每次取100,当发现钱不够100,就等妈妈存钱妈妈每次存钱2000,当发现钱小于100就存钱,并且通知小明取取钱,当大于100就等小明钱不够再存

public class XiaoMing {

    private static Byte[] bytes = new Byte[0];

    public static void main(String[] args) {
        // 取得线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (bytes) {
                    while (true) {
                        Integer money = Mother.getMoney();
                        System.out.println("小明取钱一次,余额:" + (money)+"元");                        
                        if (money==0) {
                            try {
                                System.out.println("钱不足,剩余:"+money);
                                bytes.notifyAll();
                                System.out.println("等妈妈放钱");
                                Thread.sleep(5000);
                                bytes.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }).start();
        // 放的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (bytes) {
                    while (true) {
                        Mother.add();
                        System.out.println("妈妈放钱成功");
                        bytes.notifyAll();
                        try {
                            bytes.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    }
                }
        }).start();
    }
}
 class Mother {
    private static int count = 0;

    static {
        add();
    }

    public static Integer getMoney() {
        return count-=100;
    }

    public static void add() {
        count += 2000;
    }
}

运行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/932901.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号