閱讀927 返回首頁    go 阿裏雲 go 技術社區[雲棲]


java線程學習5——線程同步之同步方法

 

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

 

 

 

最後更新:2017-04-03 07:57:25

  上一篇:go Java中的HashCode(2)之Hashset造成的內存泄露
  下一篇:go mybatis動態SQL語句