zoukankan      html  css  js  c++  java
  • java线程总结--synchronized关键字,原理以及相关的锁

      在多线程编程中,synchronized关键字非常常见,当我们需要进行“同步”操作时,我们很多时候需要该该关键字对代码块或者方法进行锁定。被synchronized锁定的代码块,只能同时有一条线程访问该代码块。

      上面是很多人的认识,当然也是我之前对synchronized关键字的浅显认识,其实上面的观点存在一定的偏差。在参考了很多文章以及自己动手测试过相关代码后,我觉得有必要记录下自己对synchronized关键字的一些理解,在这个过程,会简单说说synchronized关键字的具体实现原理。

      一、synchronized:synchronized是锁代码块还是锁对象?

      synchronized具有同步的功能,更准确说是具有互斥的锁功能,那么,它到底是锁定了相关的代码块还是说锁定了对象数据?答案是锁对象。下面就从synchronized修饰方法和修饰具体代码块两方面理解这个结论:synchronized是锁对象的。

      1、synchronized修饰方法

      废话不多说,先简单看测试代码:

      代码一

      public class SynchronizedTest1 { public static void main(String [] argStrings){ final Test1 test1 = new Test1(); new Thread(new Runnable() { public void run() { try {

      test1.firstMethod();

      } catch (InterruptedException e) {

      e.printStackTrace();

      }

      }

      }).start();

      new Thread(new Runnable() { public void run() {

      test1.secondMethod();

      }

      }).start();

      }class Test1{ public synchronized void firstMethod() throws InterruptedException{

      System.out.println("firstMethod");

      Thread.sleep(2000);

      } public void secondMethod(){

      System.out.println("secondMethod");

      }

      }

      输出结果: firstMethod secondMethod 或者 secondMethod firstMethod

      然后,看代码二

      public class SynchronizedTest1 { public static void main(String [] argStrings){ final Test1 test1 = new Test1(); new Thread(new Runnable() { public void run() { try {

      test1.firstMethod();

      } catch (InterruptedException e) {

      e.printStackTrace()

      }

      }

      }).start(); new Thread(new Runnable() { public void run() {

      test1.thirdMethod();

      }

      }).start();

      }

      }class Test1{ public synchronized void firstMethod() throws InterruptedException{

      System.out.println("firstMethod");

      Thread.sleep(2000);

      } public synchronized void thirdMethod(){

      System.out.println("thirdMethod");

      }

      }

      结果一直是:firstMethod thirdMethod

      所以,我们可以得出以下结论(在理解该结论前读者可以先假设每个对象均有一个锁对象,具体后面讲解synchronized关键字原理时会讲解):

      synchronize修饰方法时(非静态方法,静态方法稍后讨论),表示某个线程执行到该方法时会锁定当前对象,其他线程不可以调用该对象中含有synchronized关键字的方法,因为这些线程的这些方法要执行前提是要获得该对象的锁。

      就上面的例子具体说:

      在代码一中,由于secondMethod方法没有synchronized关键字修饰,该方法执行无需获取当前对象的锁,所以secondMethod和firstMethod执行是并行的;

      在代码二中,firstMethod和thirdMethod方法均有synchronized关键字修饰,两个方法执行前提是可以获取当前对象的锁,所以两者是无法同时进行的,因为同一个对象中只有一把锁。

      ok,理解上面的例子之后,估计读者理解下面的代码就简单很多了,好,上代码:

      代码三:修饰静态方法时的情形(只有一个方法有static修饰)

      public class SynchronizedTest1 { public static void main(String [] argStrings){ final Test2 test2 = new Test2(); new Thread(new Runnable() { public void run() { try {

      test2.firstMethod();

      } catch (InterruptedException e) {

      e.printStackTrace();

      }

      }

      }).start(); new Thread(new Runnable() { public void run() {

      test2.thirdMethod();

      }

      }).start();

      }

      }class Test2{ public static synchronized void firstMethod() throws InterruptedException{

      System.out.println("firstMethod");

      Thread.sleep(2000);

      } public synchronized void thirdMethod(){

      System.out.println("thirdMethod");

      }

      }

      执行结果是:firstMethod thirdMethod 或者thirdMethod firstMethod

      代码四:(都有static修饰)

      public class SynchronizedTest1 { public static void main(String [] argStrings){ final Test2 test2 = new Test2(); new Thread(new Runnable() { public void run() { try {

      test2.firstMethod();

      } catch (InterruptedException e) {

      e.printStackTrace();

      }

      }

      }).start(); new Thread(new Runnable() { public void run() {

      test2.thirdMethod();

      }

      }).start();

      }

      }class Test2{ public static synchronized void firstMethod() throws InterruptedException{

      System.out.println("firstMethod");

      Thread.sleep(2000);

      } public static synchronized void thirdMethod(){

      System.out.println("thirdMethod");

      }

      }

      执行结果是:firstMethod thirdMethod

      从上面结果我们可以知道:synchronized修饰静态方法时,它会锁定Class实例对象。

      所以代码三中由于firstMethod和thirdMethod锁定对象不同,所以他们可以并行执行;代码四中两个方法都锁定了class对象,所以无法并行执行。

      好,上面一大坨的文字,总结一句话起来就是这样:

      synchronized修饰静态方法时,它表示锁定class对象;修饰动态方法时,表示锁定当前对象(this)。

      2、synchronized修饰代码块

      其实,上面的讲解已经很明确指出了一个事实:synchronized关键字就是表示当前代码锁住了某个对象,其他需要获取该锁(即被synchronized修饰)的代码块需要被执行,必须获取该对象的锁,即等到synchronized释放锁(其实就是改代码块执行完),它才有可能被执行,只是当synchronized修饰代码块时,必须显式地指出它锁定了哪个对象而已。上代码:

      代码五:

      public class SynchronizedTest1 { public static void main(String [] argStrings){ final Test3 test3 = new Test3(); new Thread(new Runnable() { public void run() { try {

      test3.firstMethod();

      } catch (InterruptedException e) {

      e.printStackTrace();

      }

      }

      }).start(); new Thread(new Runnable() { public void run() {

      test3.thirdMethod();

      }

      }).start();

      }

      }class Test3{ public void firstMethod() throws InterruptedException{ synchronized (this) {

      System.out.println("firstMethod");

      Thread.sleep(2000);

      }无锡妇科医院 http://www.xasgyy.net/

      } public void thirdMethod(){ synchronized (this) {

      System.out.println("thirdMethod");

      }

      }

      }

      上面代码和代码二五执行效果任何区别,实现的功能也是一样的。

      当然,与直接修饰方法相比,synchronized修饰代码块时,this可以换成其他对象,我们锁定对象的代码块也可以粒度更小。

      好,上面一堆废话其实归根到底都是说明一个道理:synchronized修饰的代码,它表示锁住了某个对象,被该关键字修饰的其他线程(强调其他线程,稍后讲为什么)的方法如果要执行,也必须得到该锁,即synchronized代码块执行完。

      上面强调其他线程的意思是,如果同一个线程中被synchronized的方法,则无需获取该锁,这是合理的,具体看下面例子估计就明白我在说什么了:

      public class SynchronizedTest1 { public static void main(String [] argStrings){ final Test4 test4 = new Test4(); new Thread(new Runnable() { public void run() { try {

      test4.firstMethod();

      } catch (InterruptedException e) {

      e.printStackTrace();

      }

      }

      }).start();

      }

      }class Test4{ public synchronized void firstMethod() throws InterruptedException{

      System.out.println("firstMethod");

      Thread.sleep(2000);

      secondMethod();

      } public synchronized void secondMethod(){

      System.out.println("secondMethod");

      }

      }

      结果是:firstMethod secondMethod

      好吧,我也觉得我在讲废话,确实这是显而易见的结果:被synchronized修饰的方法如果互相嵌套调用,同一条线程中并不需要等待上一个synchronized块执行完,毕竟,这样会陷入死循环。获取锁或者说锁定对象,是针对不同线程而言的。

      二、synchronized原理详解

      1、首先理解几个锁概念:对象锁(也就重量锁),轻量锁,偏向锁

      A、对象锁(重量锁)

      在多线程环境下,大多数(后面会将为什么是大多数修饰)每个对象都会有一个monitor对象(关于monitor具体可以查看jdk api文档),这个对象其实就是上面我们解释synchronized关键字时对应的锁。这个对象锁负责管理所有访问该对象的线程,具体管理模型图可以参考下面的示意图:

      对于访问该对象的线程,并发情况下,没有抢到锁(即对象访问权)的线程,会被monitor丢进list这个队列进行等候(当然,自旋锁情况例外,后面会具体讲解什么卵是自旋锁)。而所谓的公平锁与非公平锁,就是在notify唤醒list中的等候线程时,list中的线程是按照排队顺序获得锁还是一起抢该对象的锁,前者是公平的,先等候的线程先获得锁;后者则是不公平的,抢不抢到锁,和线程等待时间无关,与运气有关。

      B、轻量锁

      显然,重量锁对于每个对象都要维护一个monitor对象,开销肯定是挺大的,jvm对此进行了一些优化,这便是轻量锁出现的原因。

      轻量锁大概是这样一种概念:尽管程序是多线程环境,但是如果访问当前对象的,该对象并不会new一个monitor,而是在对象的头部用一个标识字段(貌似是两位的二进制数)表示锁,这个就是轻量锁。在线程尝试访问该对象时,该线程会将当前线程私有空间中的对应锁标识字拷贝到对象头部,如果修改成功,表示只有一条线程访问该对象该对象继续采用轻量锁;如果发现轻量锁已经被其他线程占有锁定,jvm会将轻量锁升级为重量锁。

      C、偏向锁

      偏向锁是比轻量锁更轻量的锁:当jvm发现当前程序是但线程运行时,变会对对象采取偏向锁,当然,一旦发现有synchronized多线程执行情形,jvm会把偏向锁上升为轻量锁。

      2、synchronized如何实现

      了解了上面提到的几个锁的概念后,理解synchronized实现原理就非常容易了。

      在多线程环境下,对象对应的monitor管理着需要访问该对象的所有线程,monitor中会有个变量存储synchronized获取次数,在一个线程的中的某个synchronized代码块获取monitor之后,该变量数加一,对于synchronized嵌套情形一样如此:有多少个synchronized,对应的变量值就是多少,对于其他线程如果想获得monitor,必须等到当前占有monitor线程的所有synchronized块均执行完,每执行完一个synchronized块,标识变量值减一,变为0时,其他线程就可以开始抢锁了。

      所以,所有的管理工作均由monitor完成,它是synchronized实现的核心。

      3、其他知识的补充

      A、自旋锁

      上面提到,monitor在管理每个阻塞线程的时候,会把它们放进一个队列里面,这是针对非自旋锁,当monitor被设置为自旋锁锁时,线程不会被挂起放进队列,而是在做循环,直到获取monitor的访问权。所以自旋锁有什么存在必要呢?其实,线程的挂起和唤醒的调度过程是需要耗费cpu的,当线程持有锁的时间非常短时,我们没必要将等待线程挂起,这样会导致线程的频繁挂起和唤醒,浪费了cpu资源。当然,自旋锁中线程在做循环时肯定也会消耗资源的,所以如何选择还是要衡量调度线程花费大还是线程原地循环花费大。

      另外,针对上面情形,还有一种锁叫做自适应自旋锁,它大概解决了上面提到的一些问题;

      B、自适应自旋锁

      自适应自旋锁其实就是在自旋锁的基础上加了个自旋数的计数:当循环了一定次数后,该线程还没有获取锁时,它就被丢进队列里挂起。

  • 相关阅读:
    iOS Mapkit 定位REGcode地理位置偏移
    制作mac U盘启动
    mac git xcrun error active developer path 错误
    xcode 修改 organization name 和 company identifier
    PHP 修改配置文件后重启命名
    使用 PHP 构建的 Web 应用如何避免 XSS 攻击
    PHP 可变变量
    使用 PHP 构建的 Web 应用如何避免 XSS 攻击
    git 放弃本地修改,强制拉取更新
    PHP smarty模版引擎基本安装
  • 原文地址:https://www.cnblogs.com/djw12333/p/10973516.html
Copyright © 2011-2022 走看看