今天蹦出一个奇怪的念头:synchronized锁住的实例中是否所有方法的调用都参与锁竞争?
确认前提
实验论证
package com.example.demo.thread;/*** @description* @Author zhangpf* @Date 2022/12/6 12:53*/
public class TestMap {private String value;public synchronized void put(String val){try {Thread.sleep(4000);} catch (InterruptedException e) {e.printStackTrace();}this.value = val;}public String get(){return value;}
}
package com.example.demo.thread;/*** @description 结论:不加synchronized不参与锁竞争* @Author zhangpf* @Date 2022/12/6 12:55*/
public class Test {public static void main(String[] args) {TestMap testMap = new TestMap();new Thread(() -> {testMap.put("aaa");}, "one").start();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}new Thread(() -> {System.out.println(testMap.get());}, "two").start();}
}
运行结果
结论:不加synchronized不参与锁竞争。