码迷,mamicode.com
首页 > 编程语言 > 详细

java同步机制:使用synchronize block,还是使用synchronize method

时间:2015-01-20 17:58:16      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:同步代码块和同步方法

今天在学习java原子类的时候,遇到了这篇博客,看到了同步代码块和同步方法的区别,之前没有意识到,这里记录下。

public class CP {

	private int i = 0;

	public synchronized int synchronizedMethodGet() {
		return i;
	}

	public int synchronizedBlockGet() {
		synchronized (this) {
			return i;
		}
	}
}

 

从功能角度来说,上面两种方式没有差别,都能保证方法执行时候的原子性。从性能上来看,同步方法比同步代码块更有优势。我们使用JDK提供的javap命令,查看生成的字节码。

E:\code_space\test\bin>javap -c CP
Compiled from "CP.java"
public class CP {
  public CP();
    Code:
       0: aload_0
       1: invokespecial #10                 // Method java/lang/Object."<init>":()V
       4: aload_0
       5: iconst_0
       6: putfield      #12                 // Field i:I
       9: return

  public synchronized int synchronizedMethodGet();
    Code:
       0: aload_0
       1: getfield      #12                 // Field i:I
       4: ireturn

  public int synchronizedBlockGet();
    Code:
       0: aload_0
       1: dup
       2: astore_1
       3: monitorenter
       4: aload_0
       5: getfield      #12                 // Field i:I
       8: aload_1
       9: monitorexit
      10: ireturn
      11: aload_1
      12: monitorexit
      13: athrow
    Exception table:
       from    to  target type
           4    10    11   any
          11    13    11   any
}

 

明显可以看到:使用同步代码块,产生的字节码数更多;而同步方法则很少。


 

 

java同步机制:使用synchronize block,还是使用synchronize method

标签:同步代码块和同步方法

原文地址:http://blog.csdn.net/aitangyong/article/details/42920739

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!