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);
}
}
}
}
————————————————————————————————————————————————————————————————————————
package com.zhidi.ThreadSafe;
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);
}
}
————————————————————————————————————————————————————————————————————————
package com.zhidi.ThreadSafe;
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();
// zfb.start();