同一个对象共享同一个锁,那多个对象呢?我们通过代码来看下,
我们继续上一篇的例子:
账户类
package com.ck.thread;
import java.math.BigDecimal;
public class Account {
private String name;
private BigDecimal balance = new BigDecimal("0");
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public synchronized void add(BigDecimal amount) {
System.out.println(name + ", 开始充值,充值前余额: " + balance);
try {
Thread.sleep(2000);
balance = balance.add(amount);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + ", 结束充值,充值后余额: " + balance);
}
public synchronized void print() {
System.out.println(name + ", 当前余额: " + balance);
}
}
充值的线程:
package com.ck.thread;
import java.math.BigDecimal;
public class CzThread extends Thread{
private Account account;
public CzThread(Account account) {
this.account = account;
}
@Override
public void run() {
account.add(new BigDecimal("100"));
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
然后我们看下给账户充值:
package com.ck.thread;
import java.math.BigDecimal;
public class MainThread {
public static void main(String[] args) throws InterruptedException {
/**
* 分别建两个账户,张三和李四
*
*/
Account account1 = new Account();
account1.setName("张三");
account1.setBalance(new BigDecimal("100"));
Account account2 = new Account();
account2.setName("李四");
account2.setBalance(new BigDecimal("500"));
Thread t1 = new CzThread(account1);
t1.start();
Thread t2 = new CzThread(account2);
t2.start();
}
}
我们看下结果:
张三, 开始充值,充值前余额: 100
李四, 开始充值,充值前余额: 500
李四, 结束充值,充值后余额: 600
张三, 结束充值,充值后余额: 200
通过结果我们可以看出来,张三跟李四的充值并没有互相影响,这是因为我们分别创建了张三和李四两个对象,而锁是属于对象的,所以不影响,那怎么才可以让多个对象也共享同一个锁呢,我们下一篇会为大家介绍。