Java并发(十四)----悲观互斥与乐观重试

1. 悲观互斥

互斥实际是悲观锁的思想

例如,有下面取款的需求

interface Account {
    // 获取余额
    Integer getBalance();
​
    // 取款
    void withdraw(Integer amount);
​
    /**
     * 方法内会启动 1000 个线程,每个线程做 -10 元 的操作
     * 如果初始余额为 10000 那么正确的结果应当是 0
     */
    static void demo(Account account) {
        List<Thread> ts = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withdraw(10);
            }));
        }
        long start = System.nanoTime();
        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println(account.getBalance()
                + " cost: " + (end-start)/1000_000 + " ms");
    }
}

用互斥来保护

class AccountSync implements Account {
​
    private Integer balance;
​
    public AccountUnsafe(Integer balance) {
        this.balance = balance;
    }
​
    @Override
    public Integer getBalance() {
        synchronized (this) {
            return this.balance;
        }
    }
​
    @Override
    public void withdraw(Integer amount) {
        synchronized (this) {
            this.balance -= amount;
        }
    }
}

2. 乐观重试

另外一种是乐观锁思想,它其实不是互斥

class AccountCas implements Account {
    private AtomicInteger balance;
​
    public AccountCas(int balance) {
        this.balance = new AtomicInteger(balance);
    }
​
    @Override
    public Integer getBalance() {
        return balance.get();
    }
​
    @Override
    public void withdraw(Integer amount) {
        while(true) {
            // 获取余额的最新值
            int prev = balance.get();
            // 要修改的余额
            int next = prev - amount;
            // 真正修改
            if(balance.compareAndSet(prev, next)) {
                break;
            }
        }
    }
}
​
​
​
​
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

|旧市拾荒|

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值