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

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;
}

}


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

public class ATMTester {
private static final int NUM_OF_ATM = 10;


public static void main(String[] args) {
ATMTester tester = new ATMTester();

final Thread thread[] = new Thread[NUM_OF_ATM];
final ATM atm[] = new ATM[NUM_OF_ATM];
for (int i=0; i atm[i] = new ATM();
thread[i] = new Thread(tester.new Runner(atm[i]));
thread[i].start();
}

}

class Runner implements Runnable {
ATM atm;

Runner(ATM atm) {
this.atm = atm;
}

public void run() {
atm.login("John");
//查询余额
float bal = atm.getBalance();
try {
Thread.sleep(1); //模拟人从查询到取款之间的间隔
} catch (InterruptedException e) {
// ignore it
}

try {
System.out.println("Your balance is:" + bal);
System.out.println("withdraw:" + bal * 0.8f);
atm.withdraw(bal * 0.8f);
System.out.println("deposit:" + bal * 0.8f);
atm.deposit(bal * 0.8f);
} catch (InsufficientBalanceException e1) {
System.out.println("余额不足!");
} finally {
atm.logout();
}

}
}
}



运行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仅能对方法或者代码块进行同步。在下一篇我们将通过编写一个锁对象达到这个目的。

我们首先开发一个BusyFlag的类,类似于C++中的Simaphore。



public class BusyFlag {
protected Thread busyflag = null;
protected int busycount = 0;

public synchronized void getBusyFlag() {
while (tryGetBusyFlag() == false) {
try {
wait();
} catch (Exception e) {}
}
}

private synchronized boolean tryGetBusyFlag() {
if (busyflag == null) {
busyflag = Thread.currentThread();
busycount = 1;
return true;
}

if (busyflag == Thread.currentThread()) {
busycount++;
return true;
}
return false;
}

public synchronized void freeBusyFlag() {
if(getOwner()== Thread.currentThread()) {
busycount--;
if(busycount==0) {
busyflag = null;
notify();
}
}
}

public synchronized Thread getOwner() {
return busyflag;
}
}


注:参考Scott Oaks & Henry Wong《Java Thread》

BusyFlag有3个公开方法:getBusyFlag, freeBusyFlag, getOwner,分别用于获取忙标志、释放忙标志和获取当前占用忙标志的线程。使用这个BusyFlag也非常地简单,只需要在需要锁定的地方,调用BusyFlag的getBusyFlag(),在对锁定的资源使用完毕时,再调用改BusyFlag的freeBusyFlag()即可。下面我们开始改造上篇中的Account和ATM类,并应用BusyFlag工具类使得同时只有一个线程能够访问同一个账户的目标得以实现。首先,要改造Account类,在Account中内置了一个BusyFlag对象,并通过此标志对象对Account进行锁定和解锁:



import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

class Account {
String name;
//float amount;

BusyFlag flag = new BusyFlag();

//使用一个Map模拟持久存储
static Map storage = new HashMap();
static {
storage.put("John", new Float(1000.0f));
storage.put("Mike", new Float(800.0f));
}

static Map accounts = Collections.synchronizedMap(new HashMap());


private Account(String name) {
this.name = name;
//this.amount = ((Float)storage.get(name)).floatValue();
}

public synchronized static Account getAccount (String name) {
if (accounts.get(name) == null)
accounts.put(name, new Account(name));
return (Account) accounts.get(name);
}

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;
}

public void lock() {
flag.getBusyFlag();
}

public void unlock() {
flag.freeBusyFlag();
}
}



新的Account提供了两个用于锁定的方法:lock()和unlock(),供Account对象的客户端在需要时锁定Account和解锁Account,Account通过委托给BusyFlag来提供这个机制。另外,大家也发现了,新的Account中提供了对Account对象的缓存,同时去除了public的构造方法,改为使用一个静态工厂方法供用户获取Account的实例,这样做也是有必要的,因为我们希望所有的ATM机同时只能有一个能够对同一个Account进行操作,我们在Account上的锁定是对一个特定Account对象进行加锁,如果多个ATM同时实例化多个同一个user的Account对象,那么仍然可以同时操作同一个账户。所以,要使用这种机制就必须保证Account对象在系统中的唯一性,所以,这儿使用一个Account的缓存,并将Account的构造方法变为私有的。你也可以说,通过在Account类锁上进行同步,即将Account中的BusyFlag对象声明为static的,但这样就使同时只能有一台ATM机进行操作了。这样,在一台ATM机在操作时,全市其它的所有的ATM机都必须等待。
另外必须注意的一点是:Account中的getAccount()方法必须同步,否则,将有可能生成多个Account对象,因为可能多个线程同时到达这个方法,并监测到accounts中没有“John”的Account实例,从而实例化多个John的Account实例。s

ATM类只需作少量改动,在login方法中锁定Account,在logout方法中解锁:



public class ATM {
Account acc;

//作为演示,省略了密码验证
public synchronized boolean login(String name) {
if (acc != null)
throw new IllegalArgumentException("Already logged in!");
acc = Account.getAccount(name);
acc.lock();
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 synchronized void logout () {
acc.unlock();
acc = null;
}

}



ATMTester类不需要做任何修改即可同样运行,同时保证同一个Account同时只能由一个ATM进行操作。解决了上篇提到的多个ATM同时对同一个Account进行操作造成的问题。

在最新的Doug Lea的util.concurrent工具包中(现处于JSR166)提供了类似的并发实用类:ReentrantLock,它实现了java .util.concurrent.locks.Lock接口(将在JDK1.5中发布),它的作用也类似于我们这儿的BusyFlag,实现机制、使用方法也相似。但这是一个工业强度的可重入锁的实现类。在ReentrantLock的API文档中有它的使用示例:



Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();
}

没有评论: