并发性故事
杰纶和沛晨是一对同居冤家并且把钱存在一起,但如果不把问题解决掉他们很快就会分手,这是为什么呢?
沛晨这么想:
杰纶和我说好了不会透支花费,所以规定每个人花钱之前必须检查余额,这看起来很简单,但有一天我们就突然发现连预借现金的额度也用掉了。
事情是这样的:
杰纶需要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());
}
}
}
执行结果