gpt4 book ai didi

java - 锁是否对同步执行相同的操作?

转载 作者:行者123 更新时间:2023-11-30 10:12:55 25 4
gpt4 key购买 nike

假设我有一个线程安全的银行账户类,如下所示

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.

From the official documentation for reentrant locks

关于java - 锁是否对同步执行相同的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51625286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com