Synchronized的基本使用

Synchronized是Java中解决并发问题的一种最常用的方法,也是最简单的一种方法。

Synchronized的作用主要有三个:

  • 确保线程互斥的访问同步代码
  • 保证共享变量的修改能够及时可见
  • 有效解决重排序问题。

从语法上讲,Synchronized总共有三种用法:

  • 修饰普通方法
  • 修饰静态方法
  • 修饰代码块

接下来我就通过几个例子程序来说明一下这三种使用方式(为了便于比较,三段代码除了Synchronized的使用方式不同以外,其他基本保持一致)。

没有同步的情况:

代码段一:

     public class SynchronizedTest {public void method1(){System.out.println("Method 1 start");try {System.out.println("Method 1 execute");Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Method 1 end");}public void method2(){System.out.println("Method 2 start");try {System.out.println("Method 2 execute");Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Method 2 end");}public static void main(String[] args) {final SynchronizedTest test = new SynchronizedTest();new Thread(new Runnable() {@Overridepublic void run() {test.method1();}}).start();new Thread(new Runnable() {@Overridepublic void run() {test.method2();}}).start();}}

执行结果如下,线程1和线程2同时进入执行状态,线程2执行速度比线程1快,所以线程2先执行完成,这个过程中线程1和线程2是同时执行的。

Method 1 start
Method 1 execute
Method 2 start
Method 2 execute
Method 2 end
Method 1 end

对普通方法同步:

代码段二:

     public class SynchronizedTest {public synchronized void method1(){System.out.println("Method 1 start");try {System.out.println("Method 1 execute");Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Method 1 end");}public synchronized void method2(){System.out.println("Method 2 start");try {System.out.println("Method 2 execute");Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Method 2 end");}public static void main(String[] args) {final SynchronizedTest test = new SynchronizedTest();new Thread(new Runnable() {@Overridepublic void run() {test.method1();}}).start();new Thread(new Runnable() {@Overridepublic void run() {test.method2();}}).start();}}

执行结果如下,跟代码段一比较,可以很明显的看出,线程2需要等待线程1的method1执行完成才能开始执行method2方法。

Method 1 start
Method 1 execute
Method 1 end
Method 2 start
Method 2 execute
Method 2 end

静态方法(类)同步

代码段三:

      public class SynchronizedTest {public static synchronized void method1(){System.out.println("Method 1 start");try {System.out.println("Method 1 execute");Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Method 1 end");}public static synchronized void method2(){System.out.println("Method 2 start");try {System.out.println("Method 2 execute");Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Method 2 end");}public static void main(String[] args) {final SynchronizedTest test = new SynchronizedTest();final SynchronizedTest test2 = new SynchronizedTest();new Thread(new Runnable() {@Overridepublic void run() {test.method1();}}).start();new Thread(new Runnable() {@Overridepublic void run() {test2.method2();}}).start();}}

执行结果如下,对静态方法的同步本质上是对类的同步(静态方法本质上是属于类的方法,而不是对象上的方法),所以即使test和test2属于不同的对象,但是它们都属于SynchronizedTest类的实例,所以也只能顺序的执行method1和method2,不能并发执行。

Method 1 start
Method 1 execute
Method 1 end
Method 2 start
Method 2 execute
Method 2 end

代码块同步

代码段四:

     public class SynchronizedTest {public void method1(){System.out.println("Method 1 start");try {synchronized (this) {System.out.println("Method 1 execute");Thread.sleep(3000);}} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Method 1 end");}public void method2(){System.out.println("Method 2 start");try {synchronized (this) {System.out.println("Method 2 execute");Thread.sleep(1000);}} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Method 2 end");}public static void main(String[] args) {final SynchronizedTest test = new SynchronizedTest();new Thread(new Runnable() {@Overridepublic void run() {test.method1();}}).start();new Thread(new Runnable() {@Overridepublic void run() {test.method2();}}).start();}}

执行结果如下,虽然线程1和线程2都进入了对应的方法开始执行,但是线程2在进入同步块之前,需要等待线程1中同步块执行完成。

Method 1 start
Method 1 execute
Method 2 start
Method 1 end
Method 2 execute
Method 2 end

Synchronized 原理

如果对上面的执行结果还有疑问,也先不用急,我们先来了解Synchronized的原理,再回头上面的问题就一目了然了。我们先通过反编译下面的代码来看看Synchronized是如何实现对代码块进行同步的:

     public class SynchronizedDemo {public void method() {synchronized (this) {System.out.println("Method 1 start");}}}

反编译结果:

关于这两条指令的作用,我们直接参考JVM规范中描述:

monitorenter :

Each object is associated with a monitor. A monitor is locked if andonly if it has an owner. The thread that executes monitorenter attempts to gain ownership of the monitor associated with objectref, as follows:

  • If the entry count of the monitor associated with objectref is zero, the thread enters the monitor and sets its entry count to one. The thread is then the owner of the monitor.
  • If the thread already owns the monitor associated with objectref, it reenters the monitor, incrementing its entry count.
  • If another thread already owns the monitor associated with objectref, the thread blocks until the monitor’s entry count is zero, then tries again to gain ownership.

这段话的大概意思为:

每个对象有一个监视器锁(monitor)。当monitor被占用时就会处于锁定状态,线程执行monitorenter指令时尝试获取monitor的所有权,过程如下:

  • 如果monitor的进入数为0,则该线程进入monitor,然后将进入数设置为1,该线程即为monitor的所有者。
  • 如果线程已经占有该monitor,只是重新进入,则进入monitor的进入数加1.
  • 如果其他线程已经占用了monitor,则该线程进入阻塞状态,直到monitor的进入数为0,再重新尝试获取monitor的所有权。

monitorexit:

The thread that executes monitorexit must be the owner of the monitor associated with the instance referenced by objectref.
The thread decrements the entry count of the monitor associated with objectref. If as a result the value of the entry count is zero, the thread exits the monitor and is no longer its owner. Other threads that are blocking to enter the monitor are allowed to attempt to do so.

这段话的大概意思为:

  • 执行monitorexit的线程必须是objectref所对应的monitor的所有者。

  • 指令执行时,monitor的进入数减1,如果减1后进入数为0,那线程退出monitor,不再是这个monitor的所有者。其他被这个monitor阻塞的线程可以尝试去获取这个
    monitor 的所有权。

通过这两段描述,我们应该能很清楚的看出Synchronized的实现原理,Synchronized的语义底层是通过一个monitor的对象来完成,其实wait/notify等方法也依赖于monitor对象,这就是为什么只有在同步的块或者方法中才能调用wait/notify等方法,否则会抛出java.lang.IllegalMonitorStateException的异常的原因。

我们再来看一下同步方法的反编译结果:

源代码:

         public class SynchronizedMethod {public synchronized void method() {System.out.println("Hello World!");}}

反编译结果:

从反编译的结果来看,方法的同步并没有通过指令monitorenter和monitorexit来完成(理论上其实也可以通过这两条指令来实现),不过相对于普通方法,其常量池中多了ACC_SYNCHRONIZED标示符。

JVM就是根据该标示符来实现方法的同步的:当方法调用时,调用指令将会检查方法的 ACC_SYNCHRONIZED 访问标志是否被设置,如果设置了,执行线程将先获取monitor,获取成功之后才能执行方法体,方法执行完后再释放monitor。

在方法执行期间,其他任何线程都无法再获得同一个monitor对象。其实本质上没有区别,只是方法的同步是一种隐式的方式来实现,无需通过字节码来完成。

运行结果解释

有了对Synchronized原理的认识,再来看上面的程序就可以迎刃而解了。

代码段2结果:

虽然method1和method2是不同的方法,但是这两个方法都进行了同步,并且是通过同一个对象去调用的,所以调用之前都需要先去竞争同一个对象上的锁(monitor),也就只能互斥的获取到锁,因此,method1和method2只能顺序的执行。

代码段3结果:

虽然test和test2属于不同对象,但是test和test2属于同一个类的不同实例,由于method1和method2都属于静态同步方法,所以调用的时候需要获取同一个类上monitor(每个类只对应一个class对象),所以也只能顺序的执行。

代码段4结果:

对于代码块的同步实质上需要获取Synchronized关键字后面括号中对象的monitor,由于这段代码中括号的内容都是this,而method1和method2又是通过同一的对象去调用的,所以进入同步块之前需要去竞争同一个对象上的锁,因此只能顺序执行同步块。

总结

Synchronized是Java并发编程中最常用的用于保证线程安全的方式,其使用相对也比较简单。但是如果能够深入了解其原理,对监视器锁等底层知识有所了解,一方面可以帮助我们正确的使用Synchronized关键字,另一方面也能够帮助我们更好的理解并发编程机制,有助我们在不同的情况下选择更优的并发策略来完成任务。对平时遇到的各种并发问题,也能够从容的应对。

【多线程】Synchronized及实现原理相关推荐

  1. JUC多线程:synchronized锁机制原理 与 Lock锁机制

    前言: 线程安全是并发编程中的重要关注点,造成线程安全问题的主要原因有两点,一是存在共享数据(也称临界资源),二是存在多条线程共同操作共享数据.因此为了解决这个问题,我们可能需要这样一个方案,当存在多 ...

  2. 【死磕Java并发】—–深入分析synchronized的实现原理

    记得刚刚开始学习Java的时候,一遇到多线程情况就是synchronized,相对于当时的我们来说synchronized是这么的神奇而又强大,那个时候我们赋予它一个名字"同步", ...

  3. Synchronized及其实现原理

    并发编程中synchronized一直是元老级角色,我们称之为重量级锁.主要用在三个地方: 1.修饰普通方法,锁是当前实例对象. 2.修饰类方法,锁是当前类的Class对象. 3.修饰代码块,锁是sy ...

  4. synchronized的实现原理

    说明:本文基于Hollischuang大神的文章! ** 一:synchronized的原理 ** 在再有人问你Java内存模型是什么,就把这篇文章发给他.中我们曾经介绍过,Java语言为了解决并发编 ...

  5. 面试必备:synchronized的底层原理?

    最近更新的XX必备系列适合直接背答案,不深究,不喜勿喷. 你能说简单说一下synchronize吗? 可别真简单一句话就说完了呀~ 参考回答: synchronize是java中的关键字,可以用来修饰 ...

  6. synchronized原理_浅谈synchronized的实现原理

    Synchronized是Java中的重量级锁,在我刚学Java多线程编程时,我只知道它的实现和monitor有关,但是synchronized和monitor的关系,以及monitor的本质究竟是什 ...

  7. synchronized 的底层原理

    tip: 作为程序员一定学习编程之道,一定要对代码的编写有追求,不能实现就完事了.我们应该让自己写的代码更加优雅,即使这会费时费力. 推荐:体系化学习Java(Java面试专题) 文章目录 一.syn ...

  8. Java多线程与并发相关 — 原理

    Java多线程与并发相关 - 原理 一 synchronized同步 1. 线程安全问题的主要诱因? 存在共享资源(也称临界资源); 存在多条线程共同操作这些共享数据; 2. 解决办法. 同一时刻有且 ...

  9. start()方法和run()方法区别与多线程抢占式运行原理

    目录 start()与run()方法区别 多线程抢占式运行原理 start()与run()方法区别 我们通过一个例子来进行总结,我们写一个利用Thread创建的简单的多线程例子,然后分别执行start ...

最新文章

  1. Audio Streamer
  2. 计算机计算各科及格率,某两个班数学考试成绩如下,要求计算分析指标,用..._投资分析考试_帮考网...
  3. 【数据挖掘】特征相关性挖掘神器-线性非线性关系一键挖掘!
  4. ITK:打开一个二进制图像
  5. Pythonseleniumtesseract自动化测试随机码、验证码(Captcha)的OCR识别解决方案参考...
  6. 剖析数组名、函数名(不是指针常量,更不是指针)
  7. csv文件怎么转成excel_Java读写excel,excel转成json写入磁盘文件
  8. Django学习笔记5-url
  9. 结构方程模型_结构方程模型(Structural Equation Model, SEM) 三下
  10. 变压器励磁模型 Matlab/simulink 可用于模拟电压暂降等电能质量问题
  11. 理解RNN、LSTM、GRU和Gradient Vanishing
  12. 我的世界刷猪人塔java版_我的世界主世界僵尸猪人刷怪塔制作教程
  13. [Android]Tablayout:修改指示器indicator的宽度
  14. 在vue项目中引用萤石云播放器插件
  15. java NIO BIO和AIO
  16. Python Scipy 显著性检验
  17. C 语言的控制台输出只是 “黑底白字”吗 ?
  18. 31个爱情原则让你受用终生
  19. 清除浮动的常用的几种方法
  20. php 网页手册模板,网站表单模板

热门文章

  1. Tech.ED 2009前瞻:认识System Center
  2. hibernate 一对一(One-to-One)
  3. Android 获取SD卡路径和判断SD卡是否存在.
  4. ACM 模板--邻接表 无向图 搜索算法
  5. 分布式经典书籍--深入分布式缓存 从原理到实践
  6. golang中的空slice
  7. C++成员变量的初始化顺序问题
  8. 运算符中,优先级高低总结。
  9. 《spring揭秘》读书笔记一
  10. 令人头疼的clientTop、scrollTop、offsetTop