打印本文 打印本文 关闭窗口 关闭窗口
Java多线程同步中的两个特殊类
作者:武汉SEO闵涛  文章来源:敏韬网  点击数766  更新时间:2009/4/22 23:28:01  文章录入:mintao  责任编辑:mintao
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类做了一些改动,以便适应本篇的需要:

import java.util.HashMap;
import java.util.Map;
class Account
{
 String name;
 //float amount;
 //使用一个Map模拟持久存储
 static Map storage = new HashMap();
 static
 {
  storage.put("John", new Float(1000.0f));
  storage.put("Mike", new Float(800.0f));
 }

 public Account(String name)
 {
  //System.out.println("new account:" + name);

  this.name = name;
  //this.amount = ((Float)storage.get(name)).floatValue();
 }

 public synchronized void deposit(float amt)
 {
  float amount = ((Float)storage.get(name)).floatValue();
  storage.put(name, new Float(amount + amt));
 }

 public synchronized void withdraw(float amt)
  throws InsufficientBalanceException
  {
   float amount = ((Float)storage.get(name)).floatValue();
   if (amount >= amt) amount -= amt;
   else throw new InsufficientBalanceException();
   storage.put(name, new Float(amount));
  }

 public float getBalance()
 {
  float amount = ((Float)storage.get(name)).floatValue();
  return amount;
 }
}
  在新的Account类中,我们采用一个HashMap来存储账户信息。Account由ATM类通过login登录后使用:

public class ATM
{
 Account acc;
 //作为演示,省略了密码验证
 public boolean login(String name)
 {
  if (acc != null) throw new IllegalArgumentException("Already logged in!");
  acc = new Account(name);
  return true;
 }

 public void deposit(float amt)
 {
  acc.deposit(amt);
 }

 public void withdraw(float amt) throws InsufficientBalanceException
 {
  acc.withdraw(amt);
 }

 public float getBalance()
 {
  return acc.getBalance();
 }

 public void logout ()
 {
  acc = null;
 }
}

打印本文 打印本文 关闭窗口 关闭窗口