1、synchronized关键字是对某个对象加锁,而非代码块。
private int count = 10;
public synchronized void method1() {
count--;
System.out.println(Thread.currentThread().getName() + " count = " + count);
}
public void method2(){
synchronized (this){
count--;
System.out.println(Thread.currentThread().getName() + " count = " + count);
}
}
2、synchronized关键字对静态方法加锁时相当于对T.class加锁(其中T是类名)
private static int count = 10;
public synchronized static void method1() {
count--;
System.out.println(Thread.currentThread().getName() + " count = " + count);
}
public static void method2() {
synchronized(T.class) {
count --;
}
}
3、对业务写方法加锁,对业务读方法不加锁,容易产生脏读问题。
4、一个同步方法可以调用另外一个同步方法,一个线程已经拥有某个对象的锁,再次申请的时候仍然会得到该对象的锁。也就是说使用synchronized关键字获得的锁是可重入的。可以在子类的同步方法中调用父类的同步方法,此时依旧是可重入的。
5、程序在执行过程中,如果出现异常,默认情况使用synchronized关键字获得的锁会被释放。在第一个线程中抛出异常,其他线程就会进入同步代码区,有可能会访问到异常产生时的数据,可能会发生不一致的情况,需要非常小心的处理同步业务逻辑中的异常。