模拟银行取现。同时使用银行卡和存折取款
创建账户类,进行取现
public class Account {
public int count;
public Account(int count){
this.count = count;
}
public <span style="color:#FF0000;">synchronized</span> boolean getCash(int cash){
if(cash>count){
try {
throw new Exception("余额不足");
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count -= cash;
return true;
}
}
创建账户操作类,进行线程处理
public class AccountOperation extends Thread{
private Account account;
private String operation;
private int cash;
public AccountOperation(Account account, String operation,int cash){
this.account = account;
this.operation = operation;
this.cash = cash;
}
public void run(){
boolean result = account.getCash(cash);
if(result){
System.out.println("取现成功,取现金额为:"+cash+",卡里余额为:"+account.count);
}else{
System.out.println("取现失败,取现金额为:"+cash+",卡里余额为:"+account.count);
}
}
}
开始测试
public class Test {
public static void main(String[] args) {
Account account = new Account(5000);
AccountOperation ao1 = new AccountOperation(account,"存折",2500);
AccountOperation ao2 = new AccountOperation(account,"ATM",2600);
ao1.start();
ao2.start();
}
}
如果不加synchronized关键字结果为
or
加上synchronized后
synchronized代码块中的语句只能有一个线程在执行,一个线程没有执行完不允许另外的线程进入
原因:
任意一个对象都有一个标志位,有1和0两种状态
当程序执行到synchronized代码块的时候线程会检查对象的标志位是1还是0
如果是1则执行程序,同是将对象的标志位设置为0,其他线程执行到synchronized代码块时一看对象标志位为0 则线程会阻塞,一直等到对象的标志位为1再执行下面的程序