<h3>账户类</h3>
public class Account {
public int balance;
public Account(int balance) {
this.balance = balance;
}
public void qu(int money){
synchronized (this) {//对象锁
if(balance >= money){
System.out.println(Thread.currentThread().getName()+"当前余额为:"+balance);
System.out.println(Thread.currentThread().getName()+"取款:"+money);
balance-=money;
System.out.println(Thread.currentThread().getName()+"取款后余额为:"+balance);
}
}
}
}
取款类
public class QuKuan extends Thread {
public Account account;
public int money;
public QuKuan(Account account,int money) {
this.account = account;
this.money = money;
}
@Override
public void run() {
account.qu(money);
}
}
测试
public class Test {
public static void main(String[] args) {
Account xm = new Account(1000);
Thread wx = new QuKuan(xm,100);
wx.setName("微信");
Thread qq = new QuKuan(xm,100);
qq.setName("QQ钱包");
Thread zfb = new QuKuan(xm,100);
zfb.setName("支付宝");
wx.start();
qq.start();
<span style="white-space:pre"> </span> zfb.start();
}
}