还没看透Synchronized底层原理,你就out了!

Synchronized的底层实现原理(看这篇就够了) 谈到多线程就不得不谈到Synchronized,重要性不言而喻,今天主要分享Synchronized的底层实现。 标题Synchronized synchronized关键字解决的是多个线程之间访问资源的同步性,synchronized 翻译为中文的意思是同步,也称之为”同步锁“。 synchronized的作用是保证在同一时刻, 被修饰的代码块或方法只会有一个线程执行,以达到保证并发安全的效果。 标题Synchronized的使用方式 主要有3种使用方式: 1.修饰实例方法:作用于当前实例加锁 pu. 阅读详情

一、Synchronized的基本使用

二、Synchronized的底层原理

三、运行结果解释

四、总结

 

一、Synchronized的基本使用

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

 

Synchronized的作用主要有三个:

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

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

  3. 有效解决重排序问题。

 

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

  (1)修饰普通方法

  (2)修饰静态方法

  (3)修饰代码块

 

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

 

1、没有同步的情况:

代码段一:


 
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

 

2、对普通方法同步:

代码段2:

 


 
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

 

3、静态方法(类)同步

代码段三:

1
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

4、代码块同步

代码段四:

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的原理

 

再回头上面的问题就一目了然了。我们先通过反编译下面的代码来看看Synchronized是如何实现对代码块进行同步的:

package com.paddx.test.concurrent;
public class SynchronizedMethod {
  public synchronized void method() {
    System.out.println("Hello World!");
  }
}

反编译结果:

 

 

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

monitorenter :

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的所有权,过程如下:

 

  1. 如果monitor的进入数为0,则该线程进入monitor,然后将进入数设置为1,该线程即为monitor的所有者

     

  2. 如果线程已经占有该monitor,只是重新进入,则进入monitor的进入数加1

     

  3. 如果其他线程已经占用了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原理的认识,再来看上面的程序就可以迎刃而解了。

 

1、代码段2结果:

虽然method1和method2是不同的方法,但是这两个方法都进行了同步,并且是通过同一个对象去调用的。

 

所以调用之前都需要先去竞争同一个对象上的锁(monitor),也就只能互斥的获取到锁,因此,method1和method2只能顺序的执行。

 

2、代码段3结果:

虽然test和test2属于不同对象,但是test和test2属于同一个类的不同实例

 

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

 

3、代码段4结果:

对于代码块的同步,实质上需要获取Synchronized关键字后面括号中对象的monitor。

 

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

 

 

四 总结(非静态同步方法锁定的是类的实例(对象),静态同步方法锁定的是类)

Synchronized是Java并发编程中最常用的用于保证线程安全的方式,其使用相对也比较简单。

 

但是如果能够深入了解其原理,对监视器锁等底层知识有所了解,一方面可以帮助我们正确的使用Synchronized关键字。

 

另一方面也能够帮助我们更好的理解并发编程机制,有助我们在不同的情况下选择更优的并发策略来完成任务。对平时遇到的各种并发问题,也能够从容的应对。

本文来源:狸猫技术窝

C++硬核开发指南:从零搭建环境到现代特性实战 编程语言作为软件开发的基石,其设计哲学直接影响着系统性能与工程效率。C++以其独特的“零开销抽象”原则,在提供接近硬件底层的控制力与极致性能的同时,支持现代高级抽象,实现了性能与生产力的平衡。这一特性使其在游戏引擎、高频交易、操作系统内核等对性能有严苛要求的领域成为核心技术选型。理解C++的核心在于建立正确的计算机系统观,包括对象生命周期、内存模型及RAII(资源获取即初始化)资源管理范式。通过掌握智能指针、移动语义等现代C++特性,开发者能够有效规避内存泄漏、悬空指针等常见陷阱,构建出健壮且高效的系统。本 阅读详情

相关推荐

synchronized原理详解(通俗易懂超级好)

目标 【理解】synchronized底层原理 【掌握】synchronized 的用法 目录目标一、synchronized原理1.1 原子性1.2 可见性1.3 有序性1.4 可重入性二、synchronized 的用法三、synchronized 的底层原理3.1 对象头在JVM中存储的形式3.1.1 对象头3.1.2 对象实例数据3.1.3 对齐填充3.2 Monitor3.3 synchronized锁的优化3.3.1 synchronized锁的状态3.3.2 偏向锁3.3.3. 轻量级锁3.

拉格朗日的学习笔记 1万+

synchronized 的底层原理

synchronized 的底层原理

激流丶的博客 7447

别再只盯着YOLOv8了!手把手带你用PaddleDetection的PP-YOLOE+搞定你的第一个检测项目

本文介绍了PP-YOLOE+在目标检测领域的优势与应用实践,对比YOLOv8展示其在精度、速度和部署便利性上的突破。通过详细的代码示例和实战教程,帮助开发者快速上手PaddleDetection工具链,实现产业级目标检测项目,提升开发效率。

weixin_42701915的博客 191

Synchronized的底层实现原理(原理解析,面试必备)

synchronize的底层实现原理和monitor的实现机制

weixin_42460087的博客 3万+

从二体运动到高精度轨道:STK与MATLAB联动的轨道外推算法演进史

本文探讨了轨道外推算法从二体运动到高精度轨道预报(HPOP)的演进历程,重点分析了STK与MATLAB协同仿真环境下的技术实现与应用。通过对比不同算法的精度与适用场景,展示了HPOP在卫星参数优化和轨道设计中的优势,为航天任务规划提供了高效解决方案。

weixin_29082143的博客 703

【EPICS学习记录】根据官方教程创建一个IOC应用

参照官网给出的IOC创建教程逐步操作完成了一个IOC应用的创建,官网教程中有部分过程表述的不清晰,自己摸索之后完成了IOC的创建,并把流程记录下来。其中有一些操作不是很理解,有问题或者建议欢迎指正。

yifeng_H的博客 3667

Synchronized底层原理深入解析

synchronized是Java中的一个关键字,用于保证多线程访问共享资源时的互斥性。它可以用在方法或代码块上,用于加锁某个对象或者类,避免多个线程同时访问临界区代码,造成数据不一致或线程安全问题。为了减少锁竞争带来的性能瓶颈,Java提供了一些优化技术和策略来减少锁的粒度、提升锁的效率,从而提高多线程程序的性能。常见的优化策略有减少锁的粒度锁粗化和锁消除。特性主要功能显式锁,提供更多控制,如尝试锁、定时锁、可中断锁等用于线程等待某些任务完成后继续执行互斥控制,确保对共享资源的访问线程协调。

一碗黄焖鸡三碗米饭的博客 1558

混合编程实战:C#集成C++ PCL点云处理库,打造跨语言动态链接库

本文详细介绍了C#与C++混合编程实战,重点讲解如何通过动态链接库(DLL)集成C++ PCL点云处理库,实现跨语言协作。内容涵盖环境配置、PCL功能封装、C#调用DLL的完整方案,以及性能优化和错误处理等进阶技巧,帮助开发者高效处理大规模点云数据,提升工业软件开发效率。

weixin_42620913的博客 383

Java数组底层原理与实战避坑指南

数组是Java中最基础也最易被误解的数据结构,其本质是JVM原生支持的第一类对象,而非语法糖。理解其内存布局(对象头+长度字段+连续数据块)、类型系统表现(如[I和[Ljava.lang.String;的Class命名规则)及运行时行为(如volatile对数组元素无效),是规避越界异常、类型转换失败和并发问题的关键。在工程实践中,数组与集合互转、多维数组内存分布、基本类型与包装类数组的GC差异等场景,直接决定系统性能与稳定性。本文聚焦Java数组的JVM级实现机制与高频生产陷阱,覆盖从声明、复制、遍历到调

weixin_33885676的博客 4272

Android GNSS 模块分析(三)JNI 层

Android GNSS;定位服务;GPS;NMEA协议;LocationManagerService;导航;

Yang_Mao_Shan的博客 5169

206面试题(47~60)

Java中,synchronized锁有三种主要的状态 :偏向锁(Biased Locking):主要针对无竞争的场景,优化单线程执行的锁操作。轻量级锁(Lightweight Locking):适用于有短暂锁竞争的情况下,通过自旋避免上下文切换的开销。重量级锁(Heavyweight Locking):适用于严重锁竞争的场景,使用操作系统的互斥量(mutex)机制,保证线程安全,但会引入较大的上下文切换开销。

2301_80112070的博客 1176

用 Claude Code 快速摸清一个陌生代码库

摘要:Claude Code作为AI编码助手,能帮助开发者快速理解陌生代码库。与传统代码搜索不同,它从项目根目录出发,通过分析目录结构、配置文件等技术栈信息,提供系统级的概览。最佳实践是先通过"give me an overview"获取整体架构,再深入数据模型、认证流程等核心模块。它能生成术语表、编码规范和推荐的代码阅读路径,极大降低新成员的学习成本。相比传统方式,Claude Code能主动探索项目上下文,无需人工整理相关文件,使代码理解过程更接近有经验的工程师带教。(149字)

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 106

Java基础面试高频考点:集合框架、JVM内存模型、多线程与锁(附常见场景题)

本文全面介绍了Java编程语言的核心概念、特性及应用场景。主要内容包括: Java基础特性:平台无关性(JVM机制)、面向对象特性(封装、继承、多态)、内存管理(垃圾回收)。 数据类型与转换:8种基本数据类型及其包装类,类型转换方式(自动/强制转换),BigDecimal的精度优势。 面向对象设计:抽象类与接口区别,多态实现方式,设计原则(SOLID),内部类分类及特点。 关键特性详解: 反射机制原理及应用(动态加载、框架实现) 注解原理及运行时处理 异常处理体系(Checked/Unchecked异常)

xwhxy的博客 1025

AI大模型探索之路-认知篇1-全景透视:揭秘AIGC技术的进化之路

随着人工智能技术的突飞猛进,内容创作方式的发生了革命性的转变;从早期专业人员主导的内容生产,到现如今生成式人工智(AIGC)能创作时代;本篇文章主要讲解AIGC技术的演变历程。

寻道AI,探索AI无限可能! 1657

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Java期末复习:从核心机制到高频考点,构建高效知识图谱

面向对象编程是Java语言的基石,其封装、继承、多态三大特性构成了软件设计的核心思想。理解这些特性的底层原理,例如JVM内存模型、垃圾回收机制以及异常处理体系,是掌握Java运行机制的关键。这些知识不仅支撑着日常开发,更直接关系到程序的性能与稳定性。在实际的工程实践中,无论是构建高并发的服务器应用,还是设计可扩展的业务系统,扎实的Java理论基础都不可或缺。本文聚焦于Java期末复习,通过梳理面向对象、JVM、集合框架等核心模块,并结合Java八股文和Java面试题中的高频考点,旨在帮助读者系统性地构建知识

weixin_34109408的博客 332

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

美团后台开发笔试真题复盘:考点拆解与编程题解

动态规划是后台开发笔试中的高频考点,其核心思想是通过状态定义与转移方程将复杂问题拆解为可递推的子问题。掌握完全背包、最大连续子数组等经典模型,不仅有助于应对在线笔试,更能提升工程中的算法设计与优化能力。在计算机基础层面,TCP连接管理、数据库索引、进程线程模型等知识同样决定了一名后端工程师能否高效排查线上故障。无论是支付场景中的一致性设计,还是高并发下的缓存策略,这些技术原理都贯穿于实际业务系统。以美团校招后台开发笔试真题为例,完整复盘当年的题型构成、高频考点与两道编程题的思考过程,为准备互联网大厂校招的开

weixin_30314793的博客 428

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

一文带你理解synchronized底层原理

如果某一个资源被多个线程共享,为了避免因为资源抢占导致资源数据错乱,我们需要对线程进行同步,那么就是实现线程同步的关键字,可以说在并发控制中是必不可少的部分,今天就来看一下synchronized的使用和底层原理。

H931053的博客 894

Synchronized 底层实现原理

Synchronized 底层实现原理

快乐的小三菊的博客 812

synchronized底层原理

原子性synchronized和volatile特性上最大的区别就是原子性,volatile不具备原子性。可见性有序性可重入性 2.2 静态同步方法 2.3 同步方法块 三、synchronized的底层实现 JVM中,对象在内存中分为三块区域在Hotspot虚拟机中,Monitor是由ObjectMonitor实现的,源码时C++语言实现的,想深入了解的可以下载Hotspot的源码,我们在这里只是简单介绍一下数据结构从上图可以总结获取Monitor和释放Monitor的流程如下: 查看的字节码指

qq_39633153的博客 1432

一文详解synchronized底层实现原理

synchronized底层实现基础知识并发编程的三个问题可见性(1)什么是可见性?(2)实例演示(3)保证可见性方式一:使用`synchronized`加锁方式二:`volatile`修饰共享变量原子性(1)什么是原子性?(2)实例演示(3)保证原子性有序性(1)什么是有序性(2)实例演示(3)`as-if-serial`语义(4)保证有序性`Java`内存模型:`JMM(JavaMemoryModel)`(1)什么是`JMM`?(2)具体实现`计算机的内存模型`:现在开始聊一下`JMM`:规定关系作用.

多回头看一看 4182

深入理解synchronized底层原理,一篇文章就够了!

文章目录前言一、synchronized的特性1.1 原子性1.2 可见性1.3 有序性1.4 可重入性二、synchronized的用法三、synchronized锁的实现3.1 同步方法3.2 同步代码块四、synchronized锁的底层实现五、JVM对synchronized的优化5.1 锁膨胀5.1.1 偏向锁5.1.2 轻量级锁5.1.3 重量级锁5.2 锁消除5.3 锁粗化5.4 自...

beifengtz 1万+

Synchronized 用法和底层原理

一、对象锁和类锁 1. 对象锁 在 Java 中,每个对象都会有一个 monitor 对象,这个对象其实就是 Java 对象的锁,通常会被称为“内置锁”或“对象锁”。类的对象可以有多个,所以每个对象有其独立的对象锁,互不干扰。 2. 类锁 在 Java 中,针对每个类也有一个锁,可以称为“类锁”,类锁实际上是通过对象锁实现的,即类的 Class 对象锁。每个类只有一个 Class 对象,所...

数据与算法架构提升之路专栏 2804

synchronized 的底层原理及优化机制

原子性指一个操作或一组操作,要么全部执行且执行过程不被打断,要么全部不执行(不可分割)。比如 i++ 本质是「读取 i → 加 1 → 写入 i」三个步骤,若不加同步,多线程环境下可能被其他线程打断,导致结果错误。可见性指一个线程修改了共享变量的值后,其他线程能立刻感知到这个修改。若没有可见性保障,线程 A 修改的变量可能只存在于自己的工作内存中,未同步到主内存,线程 B 读取的仍是主内存中旧值。有序性指程序执行的顺序与代码编写的顺序一致,避免因「指令重排序」导致的多线程执行混乱。

stone_tmp的博客 759

说一下synchronized底层实现原理?_死磕synchronized关键字底层原理

前言作为Java程序员,我们都知道在多线程的情况下,为了保证线程安全,经常会使用synchronized和Lock锁。Lock锁之前写过一篇《不得不学的AQS》,已经详细讲解过Lock锁的底层原理。这次我们讲一下日常开发中常用的关键字synchronized,想要用得好,底层原理必须要搞明白。synchronized是JDK自带的一个关键字,在JDK1.5之前是一个重量级锁,所以从性能上...

weixin_29725791的博客 2432
上一篇: Volatile与Synchronized的区别、什么是重排序
下一篇: 关于倒排索引简单明了的总结
Mr_baci
博客等级 码龄9年 1万+粉丝 68原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址