gpt4 book ai didi

java - 锁和同步方法的区别

转载 作者:行者123 更新时间:2023-11-29 05:06:26 25 4
gpt4 key购买 nike

<分区>

我知道同步允许隐式锁,但它们不会产生相同的结果吗?

下面两段代码有什么区别?为什么程序员会选择使用每个?

代码块#1

class PiggyBank {    
private int balance = 0;
public int getBalance() {
return balance;
}
public synchronized void deposit(int amount) {
int newBalance = balance + amount;
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
System.out.println("IE: " + ie.getMessage());
}
balance = newBalance;
}
}

代码块#2

class PiggyBank {
private int balance = 0;
private Lock lock = new ReentrantLock();

public int getBalance() {
return balance;
}
public void deposit(int amount) {
lock.lock();
try {
int newBalance = balance + amount;
Thread.sleep(1);
balance = newBalance;
} catch (InterruptedException ie) { System.out.println("IE: " + ie.getMessage());
} finally {
lock.unlock();
}
}
}

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