本文介绍java最基本的同步方式,即使用synchronized关键字来控制一个方法的并发访问,如果一个对象已用synchronized关键字声明,那么只有一个执行线程允许去访问它,其它试图访问这个对象的线程将被挂起,直到第一个线程访问完毕。
下面通过一个小例子来学习这个概念,公司向银行存钱,取钱场景。
1:创建Account的账号类,它是银行账户的模型,只有一个双精度浮点型属性,balance.
2:实现balance的get set 方法。
3:实现AddAmount()方法,将传入的数量加到余额balance中,并且在同一时间只允许一个线程去改变这个值,使用synchronized关键字。
4:实现SubtractAmount()方法,将传入的数量从余额balance中扣除,并且在同一时间只允许一个线程去改变这个值。
具体代码:
1 public class Account { 2 3 /** 4 * Balance of the bank account 5 */ 6 private double balance; 7 8 /** 9 * Returns the balance of the account 10 * @return the balance of the account 11 */ 12 public double getBalance() { 13 return balance; 14 } 15 16 /** 17 * Establish the balance of the account 18 * @param balance the new balance of the account 19 */ 20 public void setBalance(double balance) { 21 this.balance = balance; 22 } 23 24 /** 25 * Add an import to the balance of the account 26 * @param amount import to add to the balance 27 */ 28 public synchronized void addAmount(double amount) { 29 double tmp=balance; 30 try { 31 Thread.sleep(10); 32 } catch (InterruptedException e) { 33 e.printStackTrace(); 34 } 35 tmp+=amount; balance=tmp; 36 } 37 38 /** 39 * Subtract an import to the balance of the account 40 * @param amount import to subtract to the balance 41 */ 42 public synchronized void subtractAmount(double amount) { 43 double tmp=balance; 44 try { 45 Thread.sleep(10); 46 } catch (InterruptedException e) { 47 e.printStackTrace(); 48 } 49 tmp-=amount; 50 balance=tmp; 51 } 52 53 } |