Synchronized的原理

来源:互联网 发布:c语言学徒招聘 编辑:程序博客网 时间:2024/05/23 17:41

概要

本文将对 Synchronized 进行再次深层的理解。

Synchronized 主要应用场景

Synchronized的作用

主要有三个:

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

代码形式上 Synchronized修饰场景共有三种

  1. 修饰普通方法
  2. 修饰静态方法
  3. 修饰代码块
下面分别展示三种使用场景:

一、不使用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();}}
运行结果:
Method 1 startMethod 1 executeMethod 2 startMethod 2 executeMethod 2 endMethod 1 end
分析:线程1 和 线程2同时进入运行状态, 但是由于线程2运行时间短, 所以比线程1较早结束。

二、对普通方法同步
/* *  * 对普通方法进行同步 *  * */public class SynchronizedTest2 {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 SynchronizedTest2 test = new SynchronizedTest2();new Thread(new Runnable() {@Overridepublic void run() {test.method1();}}).start();new Thread(new Runnable() {@Overridepublic void run() {test.method2();}}).start();}}
运行结果:
Method 1 startMethod 1 executeMethod 1 endMethod 2 startMethod 2 executeMethod 2 end
分析: 线程1需要等待线程2完全执行完 method1方法后, 才能执行method2方法。

三、静态方法(类)同步
/* * 对静态方法方法(类)进行同步  * */public class SynchronizedTest3 {public synchronized static 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 static 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 SynchronizedTest3 test = new SynchronizedTest3();new Thread(new Runnable() {@Overridepublic void run() {test.method1();}}).start();new Thread(new Runnable() {@Overridepublic void run() {test.method2();}}).start();}}

运行结果:
Method 1 startMethod 1 executeMethod 1 endMethod 2 startMethod 2 executeMethod 2 end

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

四、对代码块同步
/* * 对代码块进行同步  * */public class SynchronizedTest4 {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 SynchronizedTest4 test = new SynchronizedTest4();new Thread(new Runnable() {@Overridepublic void run() {test.method1();}}).start();new Thread(new Runnable() {@Overridepublic void run() {test.method2();}}).start();}}
运行结果:
Method 1 startMethod 1 executeMethod 2 startMethod 1 endMethod 2 executeMethod 2 end
分析:从运行结果上可以看出, 线程1 和 线程2同时进入了运行状态, 但是在线程2进入同步代码块之前, 必须等待线程2代码块运行完成。

Synchronized 原理

反编译下面的代码来看看Synchronized是如何实现对代码块进行同步的:
public class SynchronizedDemo {    public void method() {        synchronized (this) {            System.out.println("Method 1 start");        }    }}

编译: javac SynchronizedDemo.java 
反编译: javap -c SynchronizedDemo
imac:~ anthony$ javac SynchronizedDemo.java imac:~ anthony$ javap -c SynchronizedDemoCompiled from "SynchronizedDemo.java"public class SynchronizedDemo {  public SynchronizedDemo();    Code:       0: aload_0       1: invokespecial #1                  // Method java/lang/Object."<init>":()V       4: return  public void method();    Code:       0: aload_0       1: dup       2: astore_1       3: monitorenter       4: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;       7: ldc           #3                  // String Method 1 start       9: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V      12: aload_1      13: monitorexit      14: goto          22      17: astore_2      18: aload_1      19: monitorexit      20: aload_2      21: athrow      22: return    Exception table:       from    to  target type           4    14    17   any          17    20    17   any}



关于这两条指令的作用,我们直接参考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的异常的原因。


下面尝试编译 同步方法的代码:

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


反编译结果:

imac:~ anthony$ javac SynchronizedMethod.java imac:~ anthony$ javap -c SynchronizedMethodCompiled from "SynchronizedMethod.java"public class SynchronizedMethod {  public SynchronizedMethod();    Code:       0: aload_0       1: invokespecial #1                  // Method java/lang/Object."<init>":()V       4: return  public synchronized void method();    Code:       0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;       3: ldc           #3                  // String Hello World!       5: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V       8: return}


未完待续。。。。。

参考资源

http://www.importnew.com/23511.html
http://www.cnblogs.com/paddix/p/5367116.html