我应该使用同步方法来扩展字段吗? [英] Should I volatile the field with synchronized methods?

查看:148
本文介绍了我应该使用同步方法来扩展字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下类,

// This class should be thread-safe!!!
class BankAccount {

    private long balance; // Should it be volatile?

    synchronized void deposit(long amount) {
        // ...
        balance += amount;
    }

    synchronized void withdraw(long amount) {
        // ...
        balance -= amount;
    }
}

我应该添加 volatile 余额字段?

推荐答案

不,与 synchronized 关键字相比, volatile 是轻量级的。

No, compared with synchronized keyword, volatile is lightweight.

volatile 可以保证读者线程始终保持新鲜余额值,但它不能使余额+ =金额; 原子。 synchronized 可以同时执行这两项操作。

volatile can gurantee the reader thread always get fresh balance value, but it can not make balance += amount; atomic. synchronized can do both.

这篇关于我应该使用同步方法来扩展字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆