synchronized(this)和synchronized方法有什么区别 [英] What is the difference between synchronized(this) and synchronized method

查看:556
本文介绍了synchronized(this)和synchronized方法有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下2个示例代码:

Lets say we have these 2 sample code :

public synchronized void getSomething(){
     this.hello = "hello World";
}

这一个

public void getSomething(){
   synchronized(this){
     this.hello = "hello World";
   }
}

所以有人可以告诉我现在的区别是什么?

So some one can tell me what's the difference now?

推荐答案

两种不同的方法功能相同可能是一个非常小的性能差异:

The two different methods are functionally equivalent. There may be a very small performance difference:

在字节码级别, synchronized方法将其同步需求作为方法访问标志中的位设置进行通告。 JVM查找此位标志并进行适当的同步。

At the bytecode level, the synchronized method advertises its need for synchronization as a bit set in the method's access flag. The JVM looks for this bit flag and synchronizes appropriately.

synchronized块通过存储在类文件中的一系列字节码操作实现其同步方法的定义。

The synchronized block implements its synchronization through a sequence of bytecode operations stored in the class file's definition of the method.

因此,同步方法可能可能执行得更快,并且在字节码方面占用的空间更少。

So the synchronized method might potentially execute slightly faster and take up less space in terms of bytecode.

同样,根据规范,两者在功能上完全相同。

Again, the two are, by specification, functionally identical.

我猜测性能差异可以忽略不计风格指南应该胜出。一些编译器甚至可能将块优化为访问标志。 JIT可能会消除性能差异。

I'm guessing that the performance difference is negligible and code style guidelines should win out. Some compilers might even optimize away the block into an access flag. And JIT may take the performance difference away.

这篇关于synchronized(this)和synchronized方法有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆