比方说我有一个线程安全的银行帐户类,像这样
class BankAccount {
private long balance;
public synchronized long getBalance() {
return balance;
}
public synchronized void deposit(long amount) {
balance += amount;
}
public synchronized void withdraw(long amount) {
balance -= amount;
}
}
使用锁是否会产生相同的效果?
class BankAccount {
private long balance;
private final Lock lock = new ReentrantLock();
public long getBalance() {
try {
lock.lock();
return balance;
} finally {
lock.unlock();
}
}
public void deposit(long amount) {
try {
lock.lock();
balance += amount;
} finally {
lock.unlock();
}
}
public void withdraw(long amount) {
try {
lock.lock();
balance -= amount;
} finally {
lock.unlock();
}
}
}
答案 0 :(得分:1)
是的
ReentrantLock:可重入互斥锁,其基本行为和语义与使用同步方法和语句访问的隐式监视器锁相同,但具有扩展功能。