同步方法和静态同步方法
You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from(不同于) the lock for any instance of the class.
Java中的每一个对象都可以作为锁
对于同步方法,锁是当前实例对象。
对于静态同步方法,锁是当前对象的Class对象。
对于同步方法块,锁是synchonized括号里配置的对象。
当一个线程试图访问同步代码块时,它首先必须得到锁,退出或抛出异常时必须释放锁。如下代码,
package com.usoft;
/**
* If the method is an instance method,
* it locks the monitor associated with the instance for which it was invoked
* (that is, the object that will be known as this during execution of the body of the method).
* If the method is static, it locks the monitor associated with the Class object
* that represents the class in which the method is defined.
* Created by liyanxin on 2015/1/5.
*/
public class HelloWorld {
//静态方法加锁实际上是加在HelloWorld.class上
synchronized public static void methodA1() {
}
//加锁的范围与methodA1一致
public static void methodA2() {
synchronized (HelloWorld.class) {
}
}
//修饰在类方法上得锁,实际上是加在当前对象上也就是this
synchronized public void methodB1() {
}
//加锁的范围与methodB1一致
public void methodB2() {
synchronized (this) {
}
}
}
==========END==========