synchronize字节码解析

源java文件:

  public class TestSynchronize {

    static volatile int b;
    
    public static void main(String[] args) {

        String s = new String("xxx");
        int a = 10;
        
        
        synchronized(s){
            a++;
        }
        
        b = 10;

    }
}

字节码文件:

   public class com.learn.test.code.bytecode.TestSynchronize {
  static volatile int b;

  public com.learn.test.code.bytecode.TestSynchronize();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: new           #2                  // class java/lang/String
       3: dup
       4: ldc           #3                  // String xxx
       6: invokespecial #4                  // Method java/lang/String."<init>":(Ljava/lang/String;)V
       9: astore_1
      10: bipush        10
      12: istore_2
      13: aload_1
      14: dup
      15: astore_3
      16: monitorenter
      17: iinc          2, 1
      20: aload_3
      21: monitorexit
      22: goto          32
      25: astore        4
      27: aload_3
      28: monitorexit
      29: aload         4
      31: athrow
      32: bipush        10
      34: putstatic     #5                  // Field b:I
      37: return
    Exception table:
       from    to  target type
          17    22    25   any
          25    29    25   any
}

i++对应的字节码如下:

  17: iinc          2, 1
  20: aload_3

他们被moniterenter和moniterexit如下包围起来:

  16: monitorenter
  17: iinc          2, 1
  20: aload_3
  21: monitorexit
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值