Java高并发编程二--Synchronized及其实现原理

1、Synchronized的基本使用

上一篇<<Java高并发编程一--什么是线程>>java

Synchronized是Java中解决并发问题的一种最经常使用的方法,也是最简单的一种方法。Synchronized的做用主要有三个:(1)确保线程互斥的访问同步代码(2)保证共享变量的修改可以及时可见(3)有效解决重排序问题。从语法上讲,Synchronized总共有三种用法:git

  1. 修饰普通方法  做用至关于当前实例加锁,进入同步代码前要得到当前实例的锁
  2. 修饰静态方法  做用至关于当前类对象加锁,进入同步代码前要得到当前实例的锁
  3. 修饰代码块  指定加锁对象,对给定对象加锁,进入同步代码块要获取给定对象的锁

接下来我就经过几个例子程序来讲明一下这三种使用方式(为了便于比较,三段代码除了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*/

2、Synchronized 原理

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

package com.paddx.test.concurrent;

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

关于这两条指令的做用,咱们直接参考JVM规范中描述:并发

monitorenter :ide

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的全部权,过程以下:this

一、若是monitor的进入数为0,则该线程进入monitor,而后将进入数设置为1,该线程即为monitor的全部者。

二、若是线程已经占有该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对象。 其实本质上没有区别,只是方法的同步是一种隐式的方式来实现,无需经过字节码来完成。

3、运行结果解释

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

一、代码段2结果:

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

二、代码段3结果:

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

三、代码段4结果:

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

四synchronized的可重入性

能够看下例子项目<<码云git _oo9>>

1.可重入

若一个程序或子程序能够“在任意时刻被中断而后操做系统调度执行另一段代码,这段代码又调用了该子程序不会出错”,则称其为可重入(reentrant或re-entrant)的。即当该子程序正在运行时,执行线程能够再次进入并执行它,仍然得到符合设计时预期的结果。与多线程并发执行的线程安全不一样,可重入强调对单个线程执行时从新进入同一个子程序仍然是安全的。

2. 可重入的条件

  • 不在函数内使用静态或全局数据。
  • 不返回静态或全局数据,全部数据都由函数的调用者提供。
  • 使用本地数据(工做内存),或者经过制做全局数据的本地拷贝来保护全局数据。
  • 不调用不可重入函数。

3.可重入与线程安全

通常而言,可重入的函数必定是线程安全的,反之则不必定成立。在不加锁的前提下,若是一个函数用到了全局或静态变量,那么它不是线程安全的,也不是可重入的。若是咱们加以改进,对全局变量的访问加锁,此时它是线程安全的但不是可重入的,由于一般的枷锁方式是针对不一样线程的访问(如Java的synchronized),当同一个线程屡次访问就会出现问题。只有当函数知足可重入的四条条件时,才是可重入的。

咱们回来看synchronized,synchronized拥有强制原子性的内部锁机制,是一个可重入锁。所以,在一个线程使用synchronized方法时调用该对象另外一个synchronized方法,即一个线程获得一个对象锁后再次请求该对象锁,是永远能够拿到锁的。

在Java内部,同一个线程调用本身类中其余synchronized方法/块时不会阻碍该线程的执行,同一个线程对同一个对象锁是可重入的,同一个线程能够获取同一把锁屡次,也就是能够屡次重入。缘由是Java中线程得到对象锁的操做是以线程为单位的,而不是以调用为单位的。

五 总结

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