Java多线程同步教程--BusyFlag或Lock (上)

2014-11-23 23:19:11 · 作者: · 浏览: 0
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. class Account {
  4. String name;
  5. //float amount;
  6. //使用一个Map模拟持久存储
  7. static Map storage = new HashMap();
  8. static {
  9. storage.put("John", new Float(1000.0f));
  10. storage.put("Mike", new Float(800.0f));
  11. }
  12. public Account(String name) {
  13. //System.out.println("new account:" + name);
  14. this.name = name;
  15. //this.amount = ((Float)storage.get(name)).floatValue();
  16. }
  17. public synchronized void deposit(float amt) {
  18. float amount = ((Float)storage.get(name)).floatValue();
  19. storage.put(name, new Float(amount + amt));
  20. }
  21. public synchronized void withdraw(float amt) throws InsufficientBalanceException {
  22. float amount = ((Float)storage.get(name)).floatValue();
  23. if (amount >= amt)
  24. amount -= amt;
  25. else
  26. throw new InsufficientBalanceException();
  27. storage.put(name, new Float(amount));
  28. }
  29. public float getBalance() {
  30. float amount = ((Float)storage.get(name)).floatValue();
  31. return amount;
  32. }
  33. }


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

  1. public class ATM {
  2. Account acc;
  3. //作为演示,省略了密码验证
  4. public boolean login(String name) {
  5. if (acc != null)
  6. throw new html" target="_blank">IllegalArgument