01-锁的基本使用
Lock接口
一个例子
static class Account {
// 搞个可重入锁练手
private Lock lock = new ReentrantLock();
private Integer money;
public Account(Integer money) {
this.money = money;
}
public boolean draw(int count) {
// 加锁不要放到try里边,因为如果在获取锁(自定义锁的实现)时发生了异常,异常抛出的同时,也会导致锁无故释放
lock.lock();
try {
if (money >= count) {
System.out.println("取走" + count);
money -= count;
return true;
} else {
System.out.println("钱不够了,去关注微信公号‘大雄和你一起学编程’吧");
return false;
}
} finally {
// 写到finally,保证释放锁
lock.unlock();
}
}
}最后更新于