原标题:JAVA 同步实现原理

Synchronized的基本使用

Synchronized是Java中解决并发问题的一种最常用的方法,也是最简单的一种方法。Synchronized的作用主要有三个:

确保线程互斥的访问同步代码

保证共享变量的修改能够及时可见

有效解决重排序问题。

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

修饰普通方法

修饰静态方法

修饰代码块

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

没有同步的情况

package com.paddx.test.concurrent;

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() {

@Override

public void run() {

test.method1();

}

}).start();

new Thread(new Runnable() {

@Override

public 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

对普通方法同步

package com.paddx.test.concurrent;

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() {

@Override

public void run() {

test.method1();

}

}).start();

new Thread(new Runnable() {

@Override

public 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

静态方法(类)同步

package com.paddx.test.concurrent;

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() {

@Override

public void run() {

test.method1();

}

}).start();

new Thread(new Runnable() {

@Override

public 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

代码块同步

package com.paddx.test.concurrent;

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() {

@Override

public void run() {

test.method1();

}

}).start();

new Thread(new Runnable() {

@Override

public 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是如何实现对代码块进行同步的

package com.paddx.test.concurrent;

public class SynchronizedDemo {

public void method() {

synchronized (this) {

System.out.println("Method 1 start");

}

}

}

反编译结果

关于这两条指令的作用,我们直接参考JVM规范中描述: ` Each object is associated with a monitor. A monitor is locked if and only 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的异常的原因。

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

package com.paddx.test.concurrent;

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是通过对象内部的一个叫做监视器锁(monitor)来实现的。但是监视器锁本质又是依赖于底层的操作系统的Mutex Lock来实现的。而操作系统实现线程之间的切换这就需要从用户态转换到内核态,这个成本非常高,状态之间的转换需要相对比较长的时间,这就是为什么Synchronized效率低的原因。

因此,这种依赖于操作系统Mutex Lock所实现的锁我们称之为“重量级锁”。JDK中对Synchronized做的种种优化,其核心都是为了减少这种重量级锁的使用。JDK1.6以后,为了减少获得锁和释放锁所带来的性能消耗,提高性能,引入了“偏向锁”和“轻量级锁”。无锁 --> 偏向锁 --> 轻量级 --> 重量级

来源:winger@文哥

awingger.com/2017/10/25/JAVA同步原理分析/返回搜狐,查看更多

责任编辑:

java sync 实现原理_JAVA 同步实现原理相关推荐

  1. java aqs详解_Java AQS底层原理解析

    AQS底层原理 AQS(AbstractQueuedSynchronizer)是一个抽象同步队列,JUC(java.util.concurrent)中很多同步锁都是基于AQS实现的. AQS的基本原理 ...

  2. java同步方法完成案例_Java同步代码块和同步方法原理与应用案例详解

    本文实例讲述了java同步代码块和同步方法.分享给大家供大家参考,具体如下: 一 点睛 所谓原子性WOmoad:一段代码要么执行,要么不执行,不存在执行一部分被中断的情况.言外之意是这段代码就像原子一 ...

  3. java 同步块原理_Java同步代码块和同步方法原理与应用案例详解

    Java同步代码块和同步方法原理与应用案例详解 发布于 2020-8-7| 复制链接 摘记: 本文实例讲述了Java同步代码块和同步方法.分享给大家供大家参考,具体如下:一 点睛所谓原子性:一段代码要 ...

  4. java代码轻量级锁_Java轻量级锁原理详解(Lightweight Locking)

    转自http://www.cnblogs.com/redcreen/archive/2011/03/29/1998801.html 大家知道,Java的多线程安全是基于Lock机制实现的,而Lock的 ...

  5. java synchronized 原理_Java Synchronized的原理

    我们先通过反编译下面的代码来看看Synchronized是如何实现对代码块进行同步的: public classSynchronizedDemo{public voidmethod(){synchro ...

  6. java nio底层实现_Java NIO 底层原理

    一.概念说明 1.内核态(内核空间)和用户态(用户空间)的区别和联系? 用户空间是用户进程所在的内存区域,系统空间是操作系统所在的内存区域.为了保证内核的安全,处于用户态的程序只能访问用户空间,而处于 ...

  7. java 递归原理_Java中递归原理实例分析

    本文实例分析了Java中递归原理.分享给大家供大家参考.具体分析如下: 解释:程序调用自身的编程技巧叫做递归. 程序调用自身的编程技巧称为递归( recursion).递归做为一种算法在程序设计语言中 ...

  8. java能够运行的原理_JAVA程序运行原理分析(一)

    作为JAVA的开发人员,需要知道JAVA是如何运行的,这个需要好好思考下. (一)class文件内容 class文件包含JAVA程序执行的字节码,也就是说程序的执行是通过class里面的内容进行执行的 ...

  9. java虚拟机工作原理图_Java虚拟机工作原理

    首先我想从宏观上介绍一下Java虚拟机的工作原理.从最初的我们编写的Java源文件(.java文件)是如何一步步执行的,如下图所示,首先Java源文件经过前端编译器(javac或ECJ)将.java文 ...

  10. java虚拟机堆栈工作原理_java虚拟机工作原理?

    展开全部 从宏观上介绍一下Java虚拟机的e5a48de588b662616964757a686964616f31333363373731工作原理.从最初编写的Java源文件(.java文件)是如何一 ...

最新文章

  1. 增量备份和差异备份的区别|什么是增量差异备份
  2. matlab-绘图-直角坐标系
  3. 【笔记】基于低空无人机影像和 YOLOv3 实现棉田杂草检测
  4. boost::describe模块实现console的测试程序
  5. linux手机刷机包制作工具_ROM制作工具官方下载|ROM制作工具下载 v1.0.0.59 官方版 - 绿点软件站...
  6. Mockito –使用全局配置的SmartNull在NPE上提供更好的错误消息
  7. 计算机导论设计实验,基于抽象知识点的《计算机导论》实验软件设计
  8. linux网络编程之通信协议格式
  9. vue-cli@2的原理解析
  10. Node路由简单的处理
  11. 介绍一个小工具 Linqer
  12. javascript 模拟滚动 隐藏滚动条
  13. Android 系统源码中添加 androidx 依赖
  14. c++ 写并查集算法模板
  15. 计算机论文中期报告进展情况,自动化毕业论文中期报告进展情况怎么写
  16. 2022-2027年(新版)中国石墨烯行业竞争态势及发展前景预测报告
  17. 博客园博客使用无觅插件
  18. 树莓派查看cpu温度的命令
  19. CentOS7.6安装docker
  20. R语言ggplot2可视化:使用ggpubr包的ggviolin函数可视化小提琴图、使用add_summary函数(设置参数为median_iqr)在可视化图像中添加中位数数据点、IQR线条

热门文章

  1. matlab节约里程法_新手求大神指导,MATLAB中怎么使用节约里程法
  2. VSTO打包加载项 WPS可用 Advanced Installer
  3. 计算机图书管理系统测试用例,图书馆管理系统测试用例表
  4. oracle9i如何卸载,如何卸载oracle 9i
  5. 知识图谱-生物信息学-医学顶刊论文(Briefings in Bioinformatics-2021):生物信息学中的图表示学习:趋势、方法和应用
  6. zabbix详解(感觉作者写的有点乱,但是很详细,所以转载下来,用过zabbix一段时间后复习用)
  7. 小程序版聊天室|聊天小程序|仿微信聊天界面小程序
  8. 和平精英怎么玩?智能找图、鼠标滚轮宏按键玩吃鸡还能匹配手机?
  9. java 类方法中this_Java Eclipse 中 在类与方法调用中 (this)的用法
  10. 对广州链家网二手房数据进行分析