synchronized(this)和synchronized(A.class)
程序员文章站
2022-06-02 08:13:47
...
- 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");
}
}
推荐阅读
-
synchronized与ReentrantLock实现共享资源的消费
-
详解iOS多线程之2.NSThread的加锁@synchronized
-
Java 多线程同步 锁机制与synchronized深入解析
-
Java线程之线程同步synchronized和volatile详解
-
Java中的关键字synchronized 详解
-
Java关键字volatile和synchronized作用和区别
-
详解iOS多线程之2.NSThread的加锁@synchronized
-
详解Java利用同步块synchronized()保证并发安全
-
聊聊Java并发中的Synchronized
-
深入Synchronized和java.util.concurrent.locks.Lock的区别详解