Java同步方法锁定对象或方法? [英] Java synchronized method lock on object, or method?

查看:362
本文介绍了Java同步方法锁定对象或方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在同一个类中有2个同步方法,但每个方法访问不同的变量,那么2个线程可以同时访问这两个方法吗?锁是否发生在对象上,或者它是否与synchronized方法中的变量一样具体?

If I have 2 synchronized methods in the same class, but each accessing different variables, can 2 threads access those 2 methods at the same time? Does the lock occur on the object, or does it get as specific as the variables inside the synchronized method?

示例:

class X {

    private int a;
    private int b;

    public synchronized void addA(){
        a++;
    }

    public synchronized void addB(){
        b++;
    }

}

2个线程可以访问同一个实例X级同时执行 x.addA()和 x.addB()

Can 2 threads access the same instance of class X performing x.addA() and x.addB() at the same time?

推荐答案

如果您将方法声明为同步(正如您通过键入 public synchronized void addA())您在整个对象上进行同步,因此从同一个对象访问不同变量的两个线程无论如何都会相互阻塞。

If you declare the method as synchonized (as you're doing by typing public synchronized void addA()) you synchronize on the whole object, so two thread accessing a different variable from this same object would block each other anyway.

如果你想一次仅同步一个变量,那么两个线程在访问不同的变量时不会相互阻塞,你可以在 synchronized()块。如果 a b 是对象参考,您将使用:

If you want to synchronize only on one variable at a time, so two threads won't block each other while accessing different variables, you have synchronize on them separately in synchronized () blocks. If a and b were object references you would use:

public void addA() {
    synchronized( a ) {
        a++;
    }
}
public void addB() {
    synchronized( b ) {
        b++;
    }
}

但是因为它们是原始的你不能做这个。

But since they're primitives you can't do this.

我建议你改用AtomicInteger:

I would suggest you to use AtomicInteger instead:

import java.util.concurrent.atomic.AtomicInteger;
class X {
    AtomicInteger a;
    AtomicInteger b;
    public void addA(){
        a.incrementAndGet();
    }
    public void addB(){ 
        b.incrementAndGet();
    }
}

这篇关于Java同步方法锁定对象或方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆