java并发编程小案例(二)

本文探讨了Java中使用synchronized关键字锁定对象的方法。通过对比两种不同实现方式,解释了直接在方法上使用synchronized与使用synchronized(this)的区别。重点强调了synchronized(this)锁定的是当前对象。
public class Test1 {
    private int count = 10;

    public void f(){
        synchronized (this){
            count--;
            System.out.println(count);
        }
    }
}

简单的写法,直接将Test1的对象作为锁对象。
若从某个方法开始就synchronized (this),到结束才释放锁。那么等同于如下写法:

public class Test1 {
    private int count = 10;

    public synchronized void f(){
        count--;
        System.out.println(count);
    }
}

问1:锁定的是整段代码么?
No.是锁定的当前对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值