天天看点

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

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

package cn.xy.thread;

public class account

{

 /**

  * 账户号

  */

 private string accountno;

  * 账户余额

 private double balance;

 public account()

 {

  super();

 }

 public account(string accountno, double balance)

  this.accountno = accountno;

  this.balance = balance;

 @override

 public int hashcode()

  return accountno.hashcode();

 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)

 public double getbalance()

  return balance;

 public void setbalance(double balance)

}

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;

 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("余额不足");

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();