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


 





### Java 中 `synchronized` 和 `this` 的关系 在 Java线程编程中,`synchronized` 是一种用于控制多个线程访问共享资源的关键字。当使用 `synchronized(this)` 定义同步代码块时,意味着该代码块在同一时刻只允许一个线程执行,其他试图进入此代码块的线程将会被阻塞直到当前线程释放锁[^1]。 对于 `synchronized(this)` 来说: - **作用对象**:这里的 `this` 表示当前实例对象本身作为监视器(即锁)。因此,在同一个的不同方法之间如果都采用 `synchronized(this)` 进行保护,则这些方法不会并发执行;因为它们共用了相同的锁——就是这个对象自己。 - **适用范围**:通常适用于需要保证整个对象状态一致性的情况下。比如有一个银行账户 Account,其中有两个操作余额的方法 deposit() 和 withdraw() 都可能改变 balance 字段值。此时就可以利用 `synchronized(this)` 来防止两个线程同时修改同一笔资金而导致的数据不一致问题[^2]。 下面是一个简单的例子来展示如何使用 `synchronized(this)`: ```java public class Counter { private int count; public void increment(){ synchronized (this){ count++; } } public void decrement(){ synchronized (this){ count--; } } } ``` 在这个案例里,无论是调用 `increment()` 方法还是 `decrement()` 方法都会先获取到当前对象(`Counter`)上的锁才能继续往下走,从而实现了对 `count` 变量的安全更新[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值