Java多线程同步教程 --上

本文通过一个银行账户的示例,介绍了Java中多线程同步的重要性,并探讨了使用synchronized关键字的局限性。
  Java语言内置了synchronized关键字用于对多线程进行同步,大大方便了Java中多线程程序的编写。但是仅仅使用synchronized关键字还不能满足对多线程进行同步的所有需要。大家知道,synchronized仅仅能够对方法或者代码块进行同步,如果我们一个应用需要跨越多个方法进行同步,synchroinzed就不能胜任了。在C++中有很多同步机制,比如信号量、互斥体、临届区等。在Java中也可以在synchronized语言特性的基础上,在更高层次构建这样的同步工具,以方便我们的使用。
    当前,广为使用的是由Doug Lea编写的一个Java中同步的工具包,可以在这儿了解更多这个包的详细情况:
     http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html
    该工具包已经作为JSR166正处于JCP的控制下,即将作为JDK1.5的正式组成部分。本文并不打算详细剖析这个工具包,而是对多种同步机制的一个介绍,同时给出这类同步机制的实例实现,这并不是工业级的实现。但其中会参考Doug Lea的这个同步包中的工业级实现的一些代码片断。
    本例中还沿用上篇中的Account类,不过我们这儿编写一个新的ATM类来模拟自动提款机,通过一个ATMTester的类,生成10个ATM线程,同时对John账户进行查询、提款和存款操作。Account类做了一些改动,以便适应本篇的需要:

  1. import java.util.HashMap;
  2. import java.util.Map;
  3.  
  4. class Account {
  5.     String name;
  6.     //float amount;
  7.     
  8.     //使用一个Map模拟持久存储
  9.     static Map storage = new HashMap();
  10.     static {
  11.         storage.put("John"new Float(1000.0f));
  12.         storage.put("Mike"new Float(800.0f));
  13.     }    
  14.     
  15.     
  16.     public Account(String name) {
  17.         //System.out.println("new account:" + name);
  18.         this.name = name;
  19.         //this.amount = ((Float)storage.get(name)).floatValue();
  20.     }
  21.  
  22.     public synchronized void deposit(float amt) {
  23.         float amount = ((Float)storage.get(name)).floatValue();
  24.         storage.put(name, new Float(amount + amt));
  25.     }
  26.  
  27.     public synchronized void withdraw(float amt) throws InsufficientBalanceException {
  28.         float amount = ((Float)storage.get(name)).floatValue();
  29.         if (amount >= amt)
  30.             amount -= amt;
  31.         else 
  32.             throw new InsufficientBalanceException();
  33.                 
  34.         storage.put(name, new Float(amount));
  35.     }
  36.  
  37.     public float getBalance() {
  38.         float amount = ((Float)storage.get(name)).floatValue();
  39.         return amount;
  40.     }
  41. }


在新的Account类中,我们采用一个HashMap来存储账户信息。Account由ATM类通过login登录后使用:

  1. public class ATM {
  2.     Account acc;
  3.     
  4.     //作为演示,省略了密码验证
  5.     public boolean login(String name) {
  6.         if (acc != null)
  7.             throw new IllegalArgumentException("Already logged in!");
  8.         acc = new Account(name);
  9.         return true;
  10.     }
  11.     
  12.     public void deposit(float amt) {
  13.         acc.deposit(amt);
  14.     }
  15.     
  16.     public void withdraw(float amt) throws InsufficientBalanceException  {
  17.             acc.withdraw(amt);
  18.     }
  19.     
  20.     public float getBalance() {
  21.         return acc.getBalance();
  22.     }
  23.     
  24.     public void logout () {
  25.         acc = null;
  26.     }
  27.     
  28. }


下面是ATMTester,在ATMTester中首先生成了10个ATM实例,然后启动10个线程,同时登录John的账户,先查询余额,然后,再提取余额的80%,然后再存入等额的款(以维持最终的余额的不变)。按照我们的预想,应该不会发生金额不足的问题。首先看代码:

  1. public class ATMTester {
  2.     private static final int NUM_OF_ATM = 10;
  3.  
  4.  
  5.     public static void main(String[] args) {
  6.         ATMTester tester = new ATMTester();
  7.         
  8.         final Thread thread[] = new Thread[NUM_OF_ATM];
  9.         final ATM atm[] = new ATM[NUM_OF_ATM];
  10.         for (int i=0; i<NUM_OF_ATM; i++) {
  11.             atm[i] = new ATM();
  12.             thread[i] = new Thread(tester.new Runner(atm[i]));
  13.             thread[i].start();
  14.         }    
  15.         
  16.     }
  17.     
  18.     class Runner implements Runnable {
  19.         ATM atm;
  20.         
  21.         Runner(ATM atm) {
  22.             this.atm = atm;
  23.         }
  24.         
  25.         public void run() {
  26.             atm.login("John");
  27.             //查询余额
  28.             float bal = atm.getBalance();
  29.             try {
  30.                 Thread.sleep(1); //模拟人从查询到取款之间的间隔
  31.             } catch (InterruptedException e) {
  32.                 // ignore it
  33.             } 
  34.             
  35.             try {
  36.                 System.out.println("Your balance is:" + bal);
  37.                 System.out.println("withdraw:" + bal * 0.8f);
  38.                 atm.withdraw(bal * 0.8f);
  39.                 System.out.println("deposit:" + bal * 0.8f);
  40.                 atm.deposit(bal * 0.8f);
  41.             } catch (InsufficientBalanceException e1) {
  42.                 System.out.println("余额不足!");
  43.             } finally {
  44.                                     atm.logout();
  45.                            }
  46.  
  47.         }
  48.     }
  49. }


运行ATMTester,结果如下(每次运行结果都有所差异):

Your balance is:1000.0
withdraw:800.0
deposit:800.0
Your balance is:1000.0
Your balance is:1000.0
withdraw:800.0
withdraw:800.0
余额不足!
Your balance is:200.0
Your balance is:200.0
Your balance is:200.0
余额不足!
Your balance is:200.0
Your balance is:200.0
Your balance is:200.0
Your balance is:200.0
withdraw:160.0
withdraw:160.0
withdraw:160.0
withdraw:160.0
withdraw:160.0
withdraw:160.0
withdraw:160.0
deposit:160.0
余额不足!
余额不足!
余额不足!
余额不足!
余额不足!
余额不足!

为什么会出现这样的情况?因为我们这儿是多个ATM同时对同一账户进行操作,比如一个ATM查询出了余额为1000,第二个ATM也查询出了余额1000,然后两者都期望提取出800,那么只有第1个用户能够成功提出,因为在第1个提出800后,账户真实的余额就只有200了,而第二个用户仍认为余额为1000。这个问题是由于多个ATM同时对同一个账户进行操作所不可避免产生的后果。要解决这个问题,就必须限制同一个账户在某一时刻,只能由一个ATM进行操作。如何才能做到这一点?直接通过synchronized关键字可以吗?非常遗憾!因为我们现在需要对整个Account的多个方法进行同步,这是跨越多个方法的,而synchronized仅能对方法或者代码块进行同步。在下一篇我们将通过编写一个锁对象达到这个目的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值