- synchronized(this) 只能锁当前对象
- synchronized(A.class) 锁类,对类的所有实例生效
public class LockDemo{
public void method1() {
synchronized (this) {
System.out.println("method1 start");
}
}
public void method2() {
synchronized (this) {
System.out.println("method2 start");
}
}
}
-- 相当于--
public class LockDemo{
public synchronized void method1() {
System.out.println("method1 start");
}
public synchronized void method2() {
System.out.println("method2 start");
}
}
public class LockDemo{
public void method1() {
synchronized (LockDemo.class) {
System.out.println("method1 start");
}
}
public void method2() {
synchronized (LockDemo.class) {
System.out.println("method2 start");
}
}
}
-- 相当于--
public class LockDemo{
public static synchronized void method1() {
System.out.println("method1 start");
}
public static synchronized void method2() {
System.out.println("method2 start");
}
}