Java同步方法锁定对象或方法? [英] Java synchronized method lock on object, or method?
问题描述
如果我在同一个类中有 2 个同步方法,但每个方法访问不同的变量,2 个线程可以同时访问这 2 个方法吗?锁定发生在对象上,还是像同步方法中的变量一样具体?
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?
推荐答案
如果您将方法声明为 synchronized(就像您通过键入 public synchronized void addA()code>) 你在 整个 对象上同步,所以两个线程从同一个对象访问不同的变量无论如何都会相互阻塞.
If you declare the method as synchronized (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:
import java.util.concurrent.atomic.AtomicInteger;
class X {
AtomicInteger a;
AtomicInteger b;
public void addA(){
a.incrementAndGet();
}
public void addB(){
b.incrementAndGet();
}
}
这篇关于Java同步方法锁定对象或方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!