简单说明并发性问题——head first java 504

并发性故事

杰纶和沛晨是一对同居冤家并且把钱存在一起,但如果不把问题解决掉他们很快就会分手,这是为什么呢?

沛晨这么想:
杰纶和我说好了不会透支花费,所以规定每个人花钱之前必须检查余额,这看起来很简单,但有一天我们就突然发现连预借现金的额度也用掉了。

事情是这样的:

杰纶需要5万元上夜店,查了一下余额还有10万,是可以提钱的,但他没有先提钱,反而先去睡了一觉(线程中的睡眠)。

沛晨回家时杰纶还在睡,而沛晨想买个10万的包包,因此查了一下余额,发现足够(还有10万杰纶还没醒来取钱),真是太幸运了。然后沛晨把钱提了出去,拿去买包包,接着杰纶醒了,又把钱提去上夜店,问题就由此产生了。

代码描绘并发性问题

import java.util.concurrent.ThreadPoolExecutor;

class BankAccount{
    private int balance = 100;

    public int getBalance(){
        return balance;
    }

    //取款
    public void withDraw(int amout){
        balance-=amout;
    }
}

public class RyanAndMonicaJob implements Runnable {
    private BankAccount account = new BankAccount();

    public static void main(String[] args) {
        RyanAndMonicaJob theJob = new RyanAndMonicaJob();
        Thread Ryan = new Thread(theJob,"Ryan");
        Thread Monica = new Thread(theJob);
        Monica.setName("Monica");
        Ryan.start();
        Monica.start();
    }

    public void run(){
        for(int i=0;i<10;i++)
            makeWithdraw(10);
    }

    private void makeWithdraw(int amout){
        int balance = account.getBalance();

        if(balance>=amout){
            try{
                System.out.println(Thread.currentThread().getName()+" is about to withdraw.");
                Thread.sleep(500);
            }catch(InterruptedException ex){
                ex.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" woke up.");
            account.withDraw(amout);
            System.out.println(Thread.currentThread().getName()+" completes the withdraw.");
        }
        else{
            System.out.println("Sorry not enough for "+Thread.currentThread().getName());
        }
    }
}

执行结果
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值