java執行緒學習5——執行緒同步之同步方法

科技探索者發表於2017-11-20

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;

 }

 /**

  * 同步方法,同步方法的監視器是this,同步方法可以將該類變為執行緒安全的類
  * 任何時候只有一個執行緒獲得對Account物件的鎖定,然後進入draw方法進行取錢
  */

 public synchronized void draw(double drawAmount)
 {

  if (balance >= drawAmount)

  {

   System.out.println(Thread.currentThread().getName() + “取出鈔票成功” + drawAmount);

   balance -= drawAmount;

   System.out.println(“餘額為” + balance);

  }

  else

  {

   System.out.println(“餘額不足”);

  }

 }

 /*只提供Getters,不提供Setters,確保安全*/

 public String getAccountNo()

 {

  return accountNo;

 }

 public double getBalance()

 {

  return 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;

 }

 @Override

 public void run()

 {

  ac.draw(drawAmount);

 }

}

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/1058849如需轉載請自行聯絡原作者


woshixuye111


相關文章