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;
  • 括号中为类

相关内容

热门资讯

CommonsCollecti... Commons Collections简介 Apache Commons是Apache软件基金会的项...
“面壁虚构”的意思 “面壁虚构”的意思 成语拼音: [miàn bì xū gòu] ...
山旮旯儿的成语解释 山旮旯儿的成语解释  【成语原文】:山旮旯儿  【标准发音】:shān gā lá ér  【繁体写...
“没世不渝”的意思 “没世不渝”的意思 成语拼音: [méi shì bù yú] ...
处罚合同范本大全优选8篇 处罚合同范本大全 第一篇甲方:___________________乙方:_____________...
shell-函数和数组-4 shell函数 完成特定功能的代码片段,函数必须先定义才能使用。 定义函数调用函数取消...
“扬眉抵掌”的意思 “扬眉抵掌”的意思 成语拼音: [yáng méi dǐ zhǎng] ...
“大卸八块”的意思 “大卸八块”的意思 成语拼音: [dà xiè bā kuài] ...
自助活动安全免责协议书   导语:协议免责既可以采用书面形式也可以采用口头形式,既可以明示做出也可以默示做出。但是采用书面形...
和二房东签合同范本精选21篇 和二房东签合同范本 第一篇出租方(甲方):_________________承租方(乙方):____...
【Android笔记84】An... 这篇文章,主要接收Android之使用MediaRecorder录制音频文件。 目录 一、录制音频...
C++ STL常用的排序算法、... 1 常用排序算法 学习目标: 掌握常用的排序算法 算法简介: sort ...
大数据技术之Hive 第1章 Hive入门1.1 什么是Hive1)Hive简介Hive是由Facebook...
设备修缮类合同范本共18篇 设备修缮类合同范本 第一篇甲方:乙方:甲、乙双方就甲方委托乙方对甲方的机械设备进行维修事宜,经协商一...
婚前签下协议书范文(优选20... 婚前签下协议书范文 第一篇甲乙双方经自由恋爱,双方准备结婚,都愿共筑爱巢,白头到老,但为防止今后可能...
苗木买卖合同范本推荐19篇 苗木买卖合同范本 第一篇供方:______________需方:______________一、品种...
个人租房合同书样本 个人租房合同书样本出租方(甲方):xxx,男/女,xxxx年xx月xx日出生,身份证号码xxxxxx...
pandas学习(二)数据的引... 数据的引用 语法说明df[label]指定DataFrame对象的列标签并选择列df[[label1...
有哪些好看颜值高的蓝牙耳机?高... 我们在选购的时候不仅仅看看参数,还要看颜值,小巧轻便,时尚...
台州出租塔吊合同范本共11篇 台州出租塔吊合同范本 第一篇出租方(甲方):_________承租方(乙方):_________甲、...