我們首先開發一個BusyFlag的類
public class BusyFlag {
protected Thread busyflag = null;
protected int busycount =
public synchronized void getBusyFlag() {
while (tryGetBusyFlag() == false) {
try {
wait();
} catch (Exception e) {}
}
}
private synchronized boolean tryGetBusyFlag() {
if (busyflag == null) {
busyflag = Thread
busycount =
return true;
}
if (busyflag == Thread
busycount++;
return true;
}
return false;
}
public synchronized void freeBusyFlag() {
if(getOwner()== Thread
busycount
if(busycount==
busyflag = null;
notify();
}
}
}
public synchronized Thread getOwner() {
return busyflag;
}
}
注
BusyFlag有
import java
import java
import java
class Account {
String name;
//float amount;
BusyFlag flag = new BusyFlag();
//使用一個Map模擬持久存儲
static Map storage = new HashMap();
static {
storage
storage
}
static Map accounts = Collections
private Account(String name) {
this
//this
}
public synchronized static Account getAccount (String name) {
if (accounts
accounts
return (Account) accounts
}
public synchronized void deposit(float amt) {
float amount = ((Float)storage
storage
}
public synchronized void withdraw(float amt) throws InsufficientBalanceException {
float amount = ((Float)storage
if (amount >= amt)
amount
else
throw new InsufficientBalanceException();
storage
}
public float getBalance() {
float amount = ((Float)storage
return amount;
}
public void lock() {
flag
}
public void unlock() {
flag
}
}
新的Account提供了兩個用於鎖定的方法
另外必須注意的一點是
ATM類只需作少量改動
public class ATM {
Account acc;
//作為演示
public synchronized boolean login(String name) {
if (acc != null)
throw new IllegalArgumentException(
acc = Account
acc
return true;
}
public void deposit(float amt) {
acc
}
public void withdraw(float amt) throws InsufficientBalanceException {
acc
}
public float getBalance() {
return acc
}
public synchronized void logout () {
acc
acc = null;
}
}
ATMTester類不需要做任何修改即可同樣運行
在最新的Doug Lea的ncurrent工具包中(現處於JSR
Lock l =
l
try {
// access the resource protected by this lock
} finally {
l
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27585.html