Java中的同步方法和同步块有什么区别? [英] What is the difference between a synchronized method and synchronized block in Java?

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

问题描述

Java中的同步方法和同步块有什么区别?

What is the difference between a synchronized method and synchronized block in Java ?

我一直在网上搜索答案,人们似乎对此不太确定:-(

I have been searching the answer on the Net, people seem to be so unsure about this one :-(

我认为两者之间没有区别,只是synch块的作用域可能更局限,因此锁定的时间更短??

My take would be there is no difference between the two, except that the synch block might be more localized in scope and hence the lock will be of lesser time ??

在使用静态方法锁定的情况下,采用什么锁定?班级锁定是什么意思?

And in case of Lock on a static method, on what is the Lock taken ? What is the meaning of a Lock on Class ?

推荐答案

同步方法将方法接收器用作锁(例如,对于非静态方法,为this;对于静态方法,则为封闭类). Synchronized块将表达式用作锁.

A synchronized method uses the method receiver as a lock (i.e. this for non static methods, and the enclosing class for static methods). Synchronized blocks uses the expression as a lock.

因此,锁定预期对象后,以下两种方法是等效的:

So the following two methods are equivalent from locking prospective:

synchronized void mymethod() { ... }

void mymethod() {
  synchronized (this) { ... }
}

对于静态方法,该类将被锁定:

For static methods, the class will be locked:

class MyClass {
  synchronized static mystatic() { ... }

  static mystaticeq() {
    syncrhonized (MyClass.class) { ... }
  }
}

对于同步块,可以将任何非null对象用作锁:

For synchronized blocks, you can use any non-null object as a lock:

synchronized (mymap) {
  mymap.put(..., ...);
}

锁定范围

对于同步方法,该锁将在整个方法范围内保持,而在synchronized块中,该锁仅在该块范围内保持(否则称为关键部分).实际上,如果JVM可以证明可以安全地进行操作,则可以通过从synchronized块执行中删除一些操作来进行优化.

For synchronized methods, the lock will be held throughout the method scope, while in the synchronized block, the lock is held only during that block scope (otherwise known as critical section). In practice, the JVM is permitted to optimize by removing some operations out of the synchronized block execution if it can prove that it can be done safely.

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

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