synchronized(同步锁对象) {
操作共享资源的代码(核心代码)
}
锁对象要求
锁对象用任意唯一的对象好不好呢?
锁对象的规范要求
修饰符 synchronized 返回值类型 方法名称(形参列表) {
操作共享资源的代码
}
public class MoneyTest {
public static void main(String[] args) {
Account account = new Account("20220919",100000.0);
Thread mom = new DrawMoneyThread(account);
mom.setName("mom");
Thread son = new DrawMoneyThread(account);
son.setName("son");
mom.start();
son.start();
Account account1 = new Account("20220918",100000.0);
Thread dad = new DrawMoneyThread(account1);
dad.setName("dad");
Thread daughter = new DrawMoneyThread(account1);
daughter.setName("daughter");
dad.start();
daughter.start();
}
}
class DrawMoneyThread extends Thread{
private Account account;
public DrawMoneyThread(Account account) {
this.account = account;
}
@Override
public void run() {
account.drawMoney(100000);
}
}
public class Account {
private String cardCode;
private double money;
private Object lock = new Object();
public Account() {
}
public synchronized void drawMoney(double money) {
System.out.println(Thread.currentThread().getName()+"准备取钱");
//synchronized (this) {
/*上锁
显示锁:使用this可以直接锁住当前对象 即账户Accout
隐式锁:写在方法的修饰符之后
非静态方法:但是一定要是非静态方法锁住的也是当前的对象this
静态方法:锁住的是当前的字节码(class)对象*/
if (this.money >= money) {
System.out.println(Thread.currentThread().getName() + "您当前还有:" + this.money
+ "取出" + money);
this.money -= money;
System.out.println("成功取出" + money + "余额为:" + this.money);
} else {
System.out.println("余额不足");
}
}
public Account(String cardCode, double money) {
this.cardCode = cardCode;
this.money = money;
}
public String getCardCode() {
return cardCode;
}
public void setCardCode(String cardCode) {
this.cardCode = cardCode;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
***上锁 ***
是同步代码块好还是同步方法好一点?