同步块 synchronized

同步块

synchronized(Obj){} Obj一定要是在动的对象,例如银行账户

package sai.company.lesson2;

public class UnsafeBank {
    public static void main(String[] args) {
        Account account =new Account(1000,"建设银行");
        new Drawing(account,50,"大傻").start();
        new Drawing(account,100,"寡妇姐").start();
    }
}


class Account{
    int money;
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

class Drawing extends Thread{
    Account account;
    int drawMoney;
    int nowMoney;
    boolean flag=true;
    public Drawing(Account account,int drawMoney,String name) {
        super(name);
        this.account = account;
        this.drawMoney = drawMoney;
    }

    @Override
    public  void run() {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (account){
        }
        do{
            if((account.money-drawMoney<0)){
                System.out.println(this.getName()+"账户里没有钱");
                flag=false;
                return ;
            }
            account.money=account.money-drawMoney;
            nowMoney=nowMoney+drawMoney;
            System.out.println(this.getName()+"取了"+drawMoney+"余额为"+account.money);
            //System.out.println(this.getName()+"手里的钱"+nowMoney);
        }while (flag);

    }



}

必须配合sleep使用

展开阅读全文
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值