synchronized的使用场景可以归结为3种:
① 修饰静态方法,给当前类对象加锁,进入同步方法时需要获得类对象的锁
② 修饰实例方法,给当前实例变量加锁,进入同步方法时需要获得当前实例的锁
③ 修饰同步方法块,指定加锁对象(可以是实例对象,也可以是类变量),对给定对象加锁,进入同步方法块时需要获得加锁对象的锁
1、静态方法
Class BankAccount{
private static int accountNum; // 一共有多少个银行账号
public static synchronized void setAccountNum(){
accountNum = accountNum + 1;
}
}
2、成员方法
public class BankAccount{
private double balance;
private static Logger logger = LoggerFactory.getLogger(BankAccount.class);
public synchronized void deposite(double moneyToAdd){
String threadName = Thread.currentThread().getName();
logger.info(threadName + "--当前银行余额为:" + this.balance);
balance = balance + moneyToAdd;
logger.info(threadName + "--存后银行余额为:" + this.balance);
}
}
3、同步代码块,块对象是实例对象
public class BankAccount{
private double balance;
private static Logger logger = LoggerFactory.getLogger(BankAccount.class);
public void deposite(double moneyToAdd){
String threadName = Thread.currentThread().getName();
logger.info(threadName + "--当前银行余额为:" + this.balance);
synchronized(this){
balance = balance + moneyToAdd;
}
logger.info(threadName + "--存后银行余额为:" + this.balance);
}
}
4、同步代码块,块对象是类对象
Class BankAccount{
private static int accountNum; // 一共有多少个银行账号
public synchronized void setAccountNum(){
synchronized(BankAccount.class){
accountNum = accountNum + 1;
}
}
}