Synchronized的原理
来源:互联网 发布:c语言学徒招聘 编辑:程序博客网 时间:2024/05/23 17:41
概要
Synchronized 主要应用场景
Synchronized的作用
主要有三个:
- 确保线程互斥的访问同步代码
- 保证共享变量的修改能够及时可见
- 有效解决重排序问题。
代码形式上 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
/* * 对代码块进行同步 * */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 原理
public class SynchronizedDemo { public void method() { synchronized (this) { System.out.println("Method 1 start"); } }}
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}
未完待续。。。。。
参考资源
- Java的synchronized原理
- Java的synchronized原理
- synchronized锁的原理
- Synchronized的原理
- Volatile和Synchronized的原理
- Synchronized的实现与原理
- synchronized的用法和原理
- Synchronized原理
- Synchronized 原理
- synchronized 原理
- synchronized 原理
- synchronized原理
- synchronized原理
- java同步关键字Synchronized 的实现原理
- Java synchronized的实现原理与应用
- synchronized和lock的实现原理
- synchronized和lock的实现原理
- 深入分析synchronized的实现原理
- 【Python】Matplotlib画图(七)——线的颜色、点的形状
- 9月8日云栖精选夜读:杭城上演阿里巴巴“春运”大片……
- MyBatis动态sql小结(一)
- 高二&高一模拟赛13 总结
- QT中给各控件增加背景图片(可缩放可旋转)的几种方法
- Synchronized的原理
- 学习笔记 2017年9月12日
- 又一惊喜!!还记得那个2000块组装出iPhone 6S的老外吗?
- dubbo深入理解(1)
- day10--进程
- 【DP】放苹果问题
- JavaScript从入门到放弃(一)
- 以两军问题为背景来演绎Basic Paxos
- LeetCode-24-Swap-Nodes-in-Pairs 链表递归水题