子类继承无法继承synchronized,如果需要在子类中对应的地方加上该关键字即可
synchronized修饰范围:
作用于调用对象时,不同对象对synchronized修饰的代码块或者方法的调用,彼此间是不影响的
作用于所有对象时,彼此之间是有影响的,需要等释放后,另一个对象才能操作
案例一
package com.mmall.concurrency.example.sync; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Slf4j public class SynchronizedExample1 { // 修饰一个代码块 public void test1(int j) { synchronized (this) { for (int i = 0; i < 10; i++) { log.info("test1 {} - {}", j, i); } } } // 修饰一个方法 public synchronized void test2(int j) { for (int i = 0; i < 10; i++) { log.info("test2 {} - {}", j, i); } } public static void main(String[] args) { SynchronizedExample1 example1 = new SynchronizedExample1(); SynchronizedExample1 example2 = new SynchronizedExample1(); ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(() -> { example1.test1(1); }); executorService.execute(() -> { example1.test1(2); }); } }
案例二
package com.mmall.concurrency.example.sync; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Slf4j public class SynchronizedExample1 { // 修饰一个代码块 public void test1(int j) { synchronized (this) { for (int i = 0; i < 10; i++) { log.info("test1 {} - {}", j, i); } } } // 修饰一个方法 public synchronized void test2(int j) { for (int i = 0; i < 10; i++) { log.info("test2 {} - {}", j, i); } } public static void main(String[] args) { SynchronizedExample1 example1 = new SynchronizedExample1(); SynchronizedExample1 example2 = new SynchronizedExample1(); ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(() -> { example1.test1(1); }); executorService.execute(() -> { example2.test1(2); }); } }
案例1 & 案例2 分析
- 这里 test1 和 test2 其实是一样的道理,因为 test1 包裹的是整个方法体代码块,相当于 test2 包裹整个方法。
- 锁的是对象,而不是方法。什么意思呢?也就是说不同对象之间执行顺序不受影响。


