package com.it;
/**
* 测试同步
*/
public class TestSynchronized {
public static void main(String[] args) {
Acount a = new Acount(100,"judy");
Drawing d1 = new Drawing(30,a);
Drawing d2 = new Drawing(10,a);
Drawing d3 = new Drawing(40,a);
d1.start();
d2.start();
d3.start();
}
}
class Acount {
int money;//余额
String aname;//账户名
int totalExpense;//总共取多少钱
public Acount(int money, String aname) {
this.money = money;
this.aname = aname;
}
}
// 模拟取款动作
class Drawing extends Thread {
int drawingNum;//取多少钱
Acount acount;//从哪个账户取
public Drawing(int drawingNum, Acount acount) {
this.drawingNum = drawingNum;
this.acount = acount;
}
@Override
public void run() {
synchronized (acount){
if (acount.money<drawingNum){
System.out.println("卡片余额不足");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
acount.totalExpense+=drawingNum;
acount.money-=drawingNum;
}
System.out.println(acount.aname+"账户余额:"+acount.money);
System.out.println(acount.aname+"一共取了:"+acount.totalExpense);
}
}