使用Lock实现异步锁

synchronized获取和释放锁都是在同一代码块中,而Lock获取和释放锁可以放在不同的代码块中,形成一种异步锁。

public class Account {

    private long userId;

    private BigDecimal amount;

    public  ReentrantLock lock;
}
public Boolean lockAccount(Account account) {
    account.lock.lock();
    System.out.println("Now, account is locked!");
    return true;
}

public Boolean unlockAccount(Account account) {
    account.lock.unlock();
    System.out.println("Now, account is unlocked!");
    return true;
}

猜你喜欢

转载自blog.csdn.net/Wengzhengcun/article/details/87861049
今日推荐