synchronized到底锁的是谁、何时生效
创始人
2024-01-17 16:07:22
0

一、synchronized锁的几种形式

  1. synchronized修饰普通方法
  2. synchronized修饰静态方法
  3. synchronized修饰代码块

1、synchronized修饰普通方法

简单示例

public class Test{private String age;private String name;public synchronized void print(String arg1, String arg2) {this.age = this.age + arg1;this.name = this.name + arg2;}
}

下面看一个稍微复杂的场景,main方法中启动两个线程,func1和func2均被synchronized修饰。
由于是非静态方法,锁的是当前对象data,由于func1和func2方法都被synchronized修饰,且在main方法中,是用的new出来的同一个data进行调用,于是锁的就是这个data,用到data发生资源抢占,需要排队。代码首先执行到func1,func1执行3秒,func2排队等待三秒后,执行func2。

public class Test{public static void main(String[] args) {Data data = new Data();new Thread(data::func1).start();new Thread(data::func2).start();}
}class Data{SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");public synchronized void func1(){System.out.println("func1开始执行,当前时间"+ sbf.format(new Date()));try {System.out.println("func1休息3秒,当前时间"+sbf.format(new Date()));Thread.sleep(3000);System.out.println("func1休息3秒结束,当前时间"+sbf.format(new Date()));} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func1:1111111111111111111111111111111111111111111111111");System.out.println("func1执行结束,当前时间"+ sbf.format(new Date()));}public synchronized void func2(){System.out.println("func2开始执行,当前时间"+ sbf.format(new Date()));System.out.println("func2:22222222222222222222222222222222222222222222222222");System.out.println("func2执行结束,当前时间"+ sbf.format(new Date()));}
}

在这里插入图片描述

但如果把func2方法的synchronized修饰去掉,那么运行结果如下。
因为去掉synchronized的func2不再参与data资源的抢占,main方法启动后,func的线程和func2的线程同时启动,首先到达线程1,但因为需要等待3秒,于是func2的结果率先输出,3秒后再输出func1的结果

public class Test{public static void main(String[] args) {Data data = new Data();new Thread(data::func1).start();new Thread(data::func2).start();}
}class Data{SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");public synchronized void func1(){System.out.println("func1开始执行,当前时间"+ sbf.format(new Date()));try {System.out.println("func1休息3秒,当前时间"+sbf.format(new Date()));Thread.sleep(3000);System.out.println("func1休息3秒结束,当前时间"+sbf.format(new Date()));} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func1:1111111111111111111111111111111111111111111111111");System.out.println("func1执行结束,当前时间"+ sbf.format(new Date()));}public void func2(){System.out.println("func2开始执行,当前时间"+ sbf.format(new Date()));System.out.println("func2:22222222222222222222222222222222222222222222222222");System.out.println("func2执行结束,当前时间"+ sbf.format(new Date()));}
}

在这里插入图片描述

此时再做一个变化,func1和func2仍然使用synchronized修饰,但main方法中调用func1与func2每次都是新new出来的Data对象,因为普通方法锁定的是同一个对象,而不同的对象直接不发生资源抢占,因此func2无需等待func1执行完毕再执行,而是和func1同步执行。

public class Test{public static void main(String[] args) {new Thread(new Data()::func1).start();new Thread(new Data()::func2).start();}
}class Data{SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");public synchronized void func1(){System.out.println("func1开始执行,当前时间"+ sbf.format(new Date()));try {System.out.println("func1休息3秒,当前时间"+sbf.format(new Date()));Thread.sleep(3000);System.out.println("func1休息3秒结束,当前时间"+sbf.format(new Date()));} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func1:1111111111111111111111111111111111111111111111111");System.out.println("func1执行结束,当前时间"+ sbf.format(new Date()));}public synchronized void func2(){System.out.println("func2开始执行,当前时间"+ sbf.format(new Date()));System.out.println("func2:22222222222222222222222222222222222222222222222222");System.out.println("func2执行结束,当前时间"+ sbf.format(new Date()));}
}

在这里插入图片描述

2. synchronized修饰静态方法

简单示例

public class Test {public synchronized static void print(String arg1, String arg2) {System.out.println("静态方法锁");}
}

继续使用标题1中的例子,将func1及func2都修改为静态方法,然后在main方法中,new出来两个data对象分别调用,看下面的执行结果,发现虽然是两个对象,但仍然发生了资源抢占,因此synchronized修饰静态方法,锁定是当前类而不是当前对象。

同样的,去掉其中一个方法的synchronized修饰,则不会进行排队。

public class Test {public static void main(String[] args)  {new Thread(()->new Data().func1()).start();new Thread(()->new Data().func2()).start();}
}class Data {static SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");public synchronized static void func1() {System.out.println("func1开始执行,当前时间" + sbf.format(new Date()));try {System.out.println("func1休息3秒,当前时间" + sbf.format(new Date()));Thread.sleep(3000);System.out.println("func1休息3秒结束,当前时间" + sbf.format(new Date()));} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func1:1111111111111111111111111111111111111111111111111");System.out.println("func1执行结束,当前时间" + sbf.format(new Date()));}public synchronized static void func2() {System.out.println("func2开始执行,当前时间" + sbf.format(new Date()));System.out.println("func2:22222222222222222222222222222222222222222222222222");System.out.println("func2执行结束,当前时间" + sbf.format(new Date()));}
}

在这里插入图片描述

3. synchronized修饰代码块

简单示例

public class Test{private String age;private String name;private Object object = new Object();public void print(String arg1, String arg2) {synchronized (object) {this.age = this.age + arg1;}this.name = this.name + arg2;}
}

继续用标题1中的例子修改,起5个线程,去调用func1,func1调用func2,且将func2包裹在同步代码块中,用synchronized修改,锁定this对象,而this指的就是当前Data对象的实例化对象,因此五个线程均发生了资源抢占,挨个按顺序执行。synchronized同步代码块可圈定最小的锁范围,提高效率。

public class Test {public static void main(String[] args) {Data data = new Data();for (int i = 0; i < 5; i++) {new Thread(data::func1).start();}}
}class Data {static SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");public void func1() {System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());// 此处锁定this对象synchronized (this) {func2();}System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}public void func2() {try {// 休息三秒Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}
}

在这里插入图片描述
同样的,若将main方法中调用func1的对象,每次都新new出来一个采用不同的对象,则不会进行排队。

public class Test {public static void main(String[] args) {for (int i = 0; i < 5; i++) {// 每次都是不同的对象new Thread(new Data()::func1).start();}}
}class Data {static SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");public void func1() {System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());// 此处锁定this对象synchronized (this) {func2();}System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}public void func2() {try {// 休息三秒Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}
}

在这里插入图片描述
但将锁定对象换为new InstanceTest(),也没有触发排队,因为每次锁的对象都是新new出来的,锁的不是同一个,虽然调用的对象是同一个。

public class Test {public static void main(String[] args) {// 调用是同一个对象Data data = new Data();for (int i = 0; i < 5; i++) {new Thread(data::func1).start();}}
}class Data {SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");public void func1() {System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());// 此处锁定new InstanceTest()对象synchronized (new InstanceTest()) {func2();}System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}public void func2() {try {// 休息三秒Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}
}

在这里插入图片描述
将锁定对象InstanceTest移到func1方法外面变成Data类的成员变量:private InstanceTest instanceTest = new InstanceTest();,调用仍然是同一个data对象,因此Data类中new出来的InstanceTest也是同一个对象,因此会发生排队。

public class Test {public static void main(String[] args) {// 调用是同一个对象Data data = new Data();for (int i = 0; i < 5; i++) {new Thread(data::func1).start();}}
}class Data {SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");private InstanceTest instanceTest = new InstanceTest();public void func1() {System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());// 此处锁定instanceTest对象synchronized (instanceTest) {func2();}System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}public void func2() {try {// 休息三秒Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}
}

在这里插入图片描述
将锁定的对象换为Integer xxx = 1;因为Integer拆箱共享常量池,只有一份,则发生排队

public class Test {public static void main(String[] args) {// 调用是同一个对象Data data = new Data();for (int i = 0; i < 5; i++) {new Thread(data::func1).start();}}
}class Data {SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");public void func1() {System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());// 此处锁定Integer instanceTest = 1对象Integer instanceTest = 1;synchronized (instanceTest) {func2();}System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}public void func2() {try {// 休息三秒Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}
}

在这里插入图片描述
但如果将Integer new出来对象,产生了多个不同的Integer对象,就不会排队

public class Test {public static void main(String[] args) {// 调用是同一个对象Data data = new Data();for (int i = 0; i < 5; i++) {new Thread(data::func1).start();}}
}class Data {SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");public void func1() {System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());// 此处锁定new Integer()对象Integer instanceTest = new Integer(1);synchronized (instanceTest) {func2();}System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}public void func2() {try {// 休息三秒Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}
}

在这里插入图片描述
将锁定的Integer instanceTest = 1;修改为Integer instanceTest = 128;不发生排队。因为jdk自动拆箱,–128到127之间的值在内存中会被重复利用,认为是一个对象,而超过这个范围的值将会被加载为多个对象,每来一次new一个Integer。因此未发生排队

public class Test {public static void main(String[] args) {// 调用是同一个对象Data data = new Data();for (int i = 0; i < 5; i++) {new Thread(data::func1).start();}}
}class Data {SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");public void func1() {System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());// 此处锁定new InstanceTest()对象Integer instanceTest = 128;synchronized (instanceTest) {func2();}System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}public void func2() {try {// 休息三秒Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}
}

在这里插入图片描述

此时我锁类。因为类只有一个,因此会发生排队

public class Test {public static void main(String[] args) {// 调用是同一个对象Data data = new Data();for (int i = 0; i < 5; i++) {new Thread(data::func1).start();}}
}class Data {SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");public void func1() {System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());// 此处锁定new Data()对象synchronized (Data.class) {func2();}System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}public void func2() {try {// 休息三秒Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());}
}

在这里插入图片描述

二、结论

1. synchronized修饰普通方法

锁定的是当前对象,当前方法的调用对象若是new出来的多份,则不发生资源抢占;只有同一个对象调用该方法时,synchronized锁才生效。

2. synchronized修饰静态方法

锁定是当前类,不论是用类调用的该方法,还是用new出来的一个或N个对象调用的该方法,都会发生资源抢占。

3. synchronized修饰代码块

锁定的是括号中的对象或类。可以认为是结合了1与2的优点与方式。括号中的对象若是一份,则synchronized锁生效,否则无效。生效情况如下:

  • 括号中的对象为this,且调用该方法的对象为同一个
  • 不论调用该方法的对象是不是同一个,括号中的对象永远是同一个,比如:Integer xxx = 1;
  • 括号中为类

相关内容

热门资讯

Springcloud 整合A... Nacos实现服务注册和配置中心 1. 概述2. 集成Nacos Discovery2.1 添加依赖...
“道三不着两”的意思 “道三不着两”的意思 成语拼音: [dào sān bù zháo liǎng] ...
“通无共有”的意思 “通无共有”的意思 成语拼音: [tōng wú gòng yǒu] ...
万丈高楼平地起成语 万丈高楼平地起成语  【成语】:万丈高楼平地起  【拼音】:wàn zhàng gāo lóu pí...
“从吾所好”的意思 “从吾所好”的意思 成语拼音: [cóng wú suǒ hào] ...
2018年国赛高教杯数学建模A... 2018年国赛高教杯数学建模 A题 高温作业专用服装设计 原题再现   在高温环境下工作时ÿ...
形容男子温柔成语 形容男子温柔成语  温润如玉  【解释】温润如玉以对珍贵美玉的触感表达对人物的赞美,修辞手法上使用了...
“救苦救难”的意思 “救苦救难”的意思 成语拼音: [jiù kǔ jiù nàn] ...
“损人害己”的意思 “损人害己”的意思 成语拼音: [sǔn rén hài jǐ] ...
Serverless:基于个性... 作者 | zzbtie 导读 云原生环境下业务大规模迭代的成本压力日益增大。我们以Serverle...
路的成语 关于路的成语大全  成语是中国传统文化的一大特色,有固定的结构形式和固定的说法,表示一定的意义,在语...
【办公类-】周计划-洗牌提取《... 背景需求:新的周计划模板上有一个“运动-集体游戏”栏目。内容来自参考用书《运动》根据新...
归纳总结大环化合物:81756... 理论分析:中文名:(R)-DOTAGA-四叔丁酯英文名:D...
Linux内核Thermal框... 本文部分内容参考 万字长文 | Thermal框架源码剖析, Linux Therma...
不想变笨小心这几种食物 现代社会,工作压力大,再加上老龄化趋势,很多人担心自己老了...
形容速度快的成语   【兵贵神速】神速:特别迅速。用兵贵在行动特别迅速。  【变化如神】神:神奇。形容变化迅速而神奇。...
“萍踪梗迹”的意思 “萍踪梗迹”的意思 成语拼音: [píng zōng gěng jì] ...
南郭先生成语故事 南郭先生成语故事  【拼音】nán guō xiān shēng  【出处】推贤之风不立,滥举之法不...
“使乖弄巧”的意思 “使乖弄巧”的意思 成语拼音: [shǐ guāi nòng qiǎo] ...
PMSM矢量控制笔记(1.1)... 前言:重新整理以前的知识和文章发现,仍然有许多地方没有学得明白ÿ...