线程不安全的问题
在不做线程安全的情况下,多个线程访问一个资源会出现线程不安全的情况,容易出现不同的线程访问不同一个资源的情况。比如下列简单2个demo运行的效果,运行就会发现,会出现重复或者本身就已经按照逻辑已经不符合条件的,会出现不应该出现的结果。
//两个去银行,线程不安全的情况下
public class UnsafeBank {
public static void main(String[] args) {
//账号
Account account = new Account(new BigDecimal("100"), "结婚基金");
Drawing you = new Drawing(account,new BigDecimal("50"),"自己");
Drawing girlFriend = new Drawing(account,new BigDecimal("100"),"女朋友");
you.start();
girlFriend.start();
}
}
//银行账号
class Account{
//余额
BigDecimal momey;
//卡名
String name;
public Account(BigDecimal momey, String name) {
this.momey = momey;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
//账户
Account account;
//取多少钱
BigDecimal drawingMoney;
//现在还有多少钱
BigDecimal nowMoney;
public Drawing(Account account, BigDecimal drawingMoney,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run(){
int result = account.momey.subtract(drawingMoney).compareTo(new BigDecimal("0"));
if( result == -1) {
System.out.println("钱不够了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 取出的钱
account