竞争条件:两个或是两个以上的线程需要共享对同一数据的存取。如果两个线程存取相同的对象,并且每一个线程都调用了一个修改该对象状态的方法。可能会产生讹误的对象,这一情况通常称为竞争条件。
如下程序,当多个线程同时更新银行账户余额,一段时间,错误不知不觉就出现了,总额要么增加,要么减少。问题在于这不是原子操作
假定两个线程同时执行指令accounts[to] += amount;
该指令可能被处理如下:
1.将accounts[to]加载到寄存器。
2.增加amount。
3.将结果写回accounts[to].
现在,假定第一个线程执行步骤1和2,然后,它被剥夺了运行权。假定第二个线程被唤醒并修改了accounts数组中的同一项。然后,第一个线程被唤醒并完成其第3步。
这样,这一动作擦去了第二个线程所做的更新。于是,总金额不在正确。
package com.bing.jia;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class UnsynchBankTest{
public static final int NACCOUNTS = 100;//这家银行有多少个账号
public static final double INITIAL_BALANCE = 1000;//每个账号开始的金额
public static void main(String[] args) {
Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE);
int i;
for(i=0;i<NACCOUNTS;i++){
TransferRunnable r = new TransferRunnable(b, i, INITIAL_BALANCE);
Thread t = new Thread(r);
t.start();
}
}
}
class Bank extends Thread{
private final double[] accounts;//数组的长度为银行账号数,数组的值为银行账号的金额
public Bank(int n,double initialBalance){
accounts = new double[n];
for(int i=0;i<accounts.length;i++){
accounts[i] = initialBalance;
}
}
public void transfer(int from,int to,double amount){
if(accounts[from]<amount){
return;
}
System.out.println("Thread.currentThread():"+Thread.currentThread());
accounts[from] -= amount;
System.out.println("转账金额数amount:"+amount+" from:"+from+" to:"+to);
accounts[to] += amount;
System.out.println("getTotalBalance()账户剩余金额:"+getTotalBalance());
}
public double getTotalBalance(){
double sum = 0;
for(double a : accounts){
sum += a;
}
return sum;
}
public int size(){
return accounts.length;
}
}
class TransferRunnable implements Runnable{
private Bank bank;
private int fromAccount;
private double maxAmount;
private int DELAY = 10;
public TransferRunnable(Bank b,int from,double max){
bank = b;
fromAccount = from;
maxAmount = max;
}
@Override
public void run() {
try {
while(true){
int toAccount = (int) (bank.size()*Math.random());//随机选一个要收账的账号Math.random()返回0-1的小数
double amount = maxAmount*Math.random();//转账的金额数,始终不能比账号总额大
bank.transfer(fromAccount, toAccount, amount);
Thread.sleep((int)(DELAY*Math.random()));
Thread.sleep(DELAY);
}
} catch (InterruptedException e) {
// TODO: handle exception
}
}
}