java线程学习4——线程同步之同步代码块

通过Java实现了一个简单的银行账户系统,并发模拟两个用户从同一账户中取款的过程,使用synchronized关键字确保了账户余额的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模拟一个场景,两个人对同一个账户同时取钱

 

package cn.xy.Thread;

public class Account
{
 /**
  * 账户号
  */
 private String accountNo;
 /**
  * 账户余额
  */
 private double balance;

 public Account()
 {
  super();
 }

 public Account(String accountNo, double balance)
 {
  super();
  this.accountNo = accountNo;
  this.balance = balance;
 }

 @Override
 public int hashCode()
 {
  return accountNo.hashCode();
 }

 @Override
 public boolean equals(Object obj)
 {
  if (null != obj && obj.getClass() == Account.class)
  {
   Account target = (Account) obj;
   return target.accountNo.equals(accountNo);
  }
  return false;
 }

 /***************************************************************************/

 public String getAccountNo()
 {
  return accountNo;
 }

 public void setAccountNo(String accountNo)
 {
  this.accountNo = accountNo;
 }

 public double getBalance()
 {
  return balance;
 }

 public void setBalance(double balance)
 {
  this.balance = balance;
 }
}

 

package cn.xy.Thread;

public class DrawThread extends Thread
{
 /**
  * 模拟账户
  */
 private Account ac;

 /**
  * 当前取钱线程希望取得的钱数
  */
 private double drawAmount;

 public DrawThread(String name, Account ac, double drawAmount)
 {
  super(name);
  this.ac = ac;
  this.drawAmount = drawAmount;
 }

 @Override
 public void run()
 {
  // 同时需要操作的账户作为同步监视器,synchronized{}中的代码被称为同步代码块
  synchronized (ac)
  {
   if (ac.getBalance() >= drawAmount)
   {
    System.out.println(getName() + "取出钞票成功" + drawAmount);
    ac.setBalance(ac.getBalance() - drawAmount);
    System.out.println("余额为" + ac.getBalance());
   }
   else
   {
    System.out.println("余额不足");
   }
  }
 }
}

 

package cn.xy.Thread;

public class Test
{
 public static void main(String[] args)
 {
  Account ac = new Account("00000001",1000);
  Thread t1 = new Thread(new DrawThread("Lily", ac, 800));
  Thread t2 = new Thread(new DrawThread("Tom", ac, 800));
  t1.start();
  t2.start();
 }
}

本文转自IT徐胖子的专栏博客51CTO博客,原文链接http://blog.51cto.com/woshixy/1058712如需转载请自行联系原作者


woshixuye111

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值