锁是否对同步执行相同的操作?
Does a lock do the same for synchronized?
假设我有一个线程安全的银行账户class看起来像这样
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();
}
}
}
是的。
ReentrantLock: A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.
假设我有一个线程安全的银行账户class看起来像这样
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();
}
}
}
是的。
ReentrantLock: A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.