您的位置:首页 > 编程语言 > Java开发

Java synchronized (this) 的含义

2016-04-18 17:10 567 查看
Synchronized Methods 和 Synchronized Statements的区别在于,前者自动帮你锁了当前调用方法的对象实例(若Static方法则锁类对象)。
Locks In Synchronized Methods

When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns

The lock release occurs even if the return was caused by an uncaught exception.

当线程调用一个synchronized method时,它将自动获取该方法的对象上的intrinsic lock,并在方法返回时候释放,即使是方法返回是由于非捕获的异常,锁也会被释放。

You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to
class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.
你或许在想当一个静态的synchronized method被调用时,会发生什么,因为一个静态方法关联的是一个类而不是对象?在这种情况,

该线程将获取这个类关联的Class对象里面的intrinsic lock。所以控制访问类静态字段的锁是不同于控制类实例的锁的

Synchronized Statements

Another way to create synchronized code is with synchronized statements. Unlike synchronized methods,
synchronized statements must specify the object that provides the intrinsic lock:

另外一个构建同步代码的方法是使用synchronized statements。不像synchronized methods,synchronized statements必须指定提供intrinsic lock的对象。

public void addName(String name) {
synchronized(this) {
lastName = name;
nameCount++;
}
nameList.add(name);
}


 





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: