Java synchronized (this) 的含义


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);
}


 





  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值