java并发编程小案例(二)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xhd731568849/article/details/88901281
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.是锁定的当前对象。

猜你喜欢

转载自blog.csdn.net/xhd731568849/article/details/88901281