Java并发编程实战(使用synchronized实现同步方法)

发表于:2015-7-23 09:21

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:有梦想的小人物    来源:51Testing软件测试网采编

#
java
分享:
  本文介绍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 }
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号