天天看點

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