使用atomic实现银行存取款

[size=xx-large]一、应用场景[/size]

[size=medium] 在通常情况下,我们在用多线程处理一个问题时,当多个线程要同时处理一个共享的数据时,往往需要通过synchronized的进行同步,在线程比较多的情况会导致锁竞争太厉害,大部分的时间都花费在了线程切换之间,而对实际的业务缺操作的相对比较少。

下面我们用java.util.concurrent.atomic来实现一个类似的功能,以银行存取款为例子:[/size]


public class AtomicAccount {


AtomicLong balance;

public AtomicAccount(long money) {
balance = new AtomicLong(money);
System.out.println("Total Money:"+balance);
}

public void deposit(long money) {
balance.addAndGet(money);
}

public void withdraw(long money,int delay) {
long oldvalue = balance.get();
if(oldvalue>=money) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
[color=red] //如果balance和oldvalue相同,则balance=oldvalue - money;
if(balance.compareAndSet(oldvalue, oldvalue - money)) {[/color]
System.out.println(Thread.currentThread().getName()+" withdraw " + money +" successfull!" + "balance="+balance);
} else {
System.out.println(Thread.currentThread().getName()+" withdraw " + money +" failed!" + "balance="+balance);
}
} else {
System.out.println(Thread.currentThread().getName()+" withdraw " + money +" balance is not enough,withdraw failed!" + "balance="+balance);
}
}
}




public class AtomicAccountTest extends Thread{

AtomicAccount account;

int delay;

public AtomicAccountTest(AtomicAccount account , int delay) {
this.account = account;
this.delay = delay;
}

public void run() {
account.withdraw(100, delay);
}

public static void main(String[] args) {

AtomicAccount account = new AtomicAccount(100);
AtomicAccountTest thread_1 = new AtomicAccountTest(account,1000);
AtomicAccountTest thread_2 = new AtomicAccountTest(account,0);

thread_1.start();
thread_2.start();
}
}




运行结果:

Total Money:100
Thread-1 withdraw 100 successfull!balance=0
Thread-0 withdraw 100 failed!balance=0


[size=xx-large]二、说明:[/size]

[size=medium]//如果balance和oldvalue相同,则balance=oldvalue - money;
执行到if(balance.compareAndSet(oldvalue, oldvalue - money)) 的时候,会判断balance与oldvalue是否相同,如果相同,说明没有程序篡改,则balance=oldvalue - money[/size]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值