synchronized安全性,小银行实例

    xiaoxiao2021-12-12  7

    package com.zhidi.anquan; public class Bank { public int yue; public Bank(int yue) { this.yue=yue; } public  void quqian(int money){ synchronized (this) { if(yue>=money){ System.out.println(Thread.currentThread().getName()+"账户余额为:"+yue); System.out.println(Thread.currentThread().getName()+"取钱:"+money); yue-=money; System.out.println(Thread.currentThread().getName()+"取钱后账户余额为:"+yue); } } }

    }

    ————————————————————————————————————————————————————

    package com.zhidi.anquan; public class Quqian extends Thread { public Bank bank; public int money; public  Quqian(Bank bank,int money){ this.bank=bank; this.money=money; } public void run() { bank.quqian(money); }

    ————————————————————————————————————————————————————————

    package com.zhidi.anquan; public class Text { public static void main(String [] args){ Bank bank = new Bank(1000); Thread wx = new Quqian(bank,100); wx.setName("微信"); Thread qq = new Quqian(bank,100); qq.setName("qq钱包"); Thread zfb = new Quqian(bank,100); zfb.setName("支付宝"); wx.start(); qq.start(); zfb.start(); } } }

    转载请注明原文地址: https://ju.6miu.com/read-900013.html

    最新回复(0)