java关键字synchronnized排队线程

package Tread;

public class Account {
    private  String accoutNo;//账号

    private  double money;//余额

//    无参构造
    public Account() {
    }

//    有参构造
    public Account(String accoutNo, double money) {
        this.accoutNo = accoutNo;
        this.money = money;
    }

    public String getAccoutNo() {
        return accoutNo;
    }

    public void setAccoutNo(String accoutNo) {
        this.accoutNo = accoutNo;
    }

    public double getMmoney() {
        return money;
    }

    public void setMmoney(double money) {
        this.money = money;
    }

//  取款方法
    public void withDraw(double money){

//        使用线程同步机制处理线程的数据冲突
        synchronized(this){//这里只有Account对象是共享的
//            ()内容必须是多线程共享的,才能达到多线程同步机制(排队)

         //开始账户的款额
        double before = this.money;

        //取钱
        double after = before - money;

        try {
//            模拟网络延迟
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //更新余额
        this.setMmoney(after);

        }
    }
}

package Tread;

public class AccountThread extends Thread {

    private  Account act;

    public AccountThread(Account act) {
        this.act = act;
    }
    @Override
    public void run() {
//        假设取款值为5000
        double money = 5000;
        act.withDraw(money);
        System.out.println(Thread.currentThread().getName()+"对"+act.getAccoutNo()+"取款成功,余额为:"+act.getMmoney());


    }
}
package Tread;

public class TestAccount {
    public static void main(String[] args) {


        Account a = new Account("act-001", 10000);
        Thread t1 = new AccountThread(a);
        Thread t2 = new AccountThread(a);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        t2.start();

    }


}

正确结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值