修饰成员方法,是对象级别的同步
class X {
private int a;
private int b;
public synchronized void addA(){
a++;
}
public synchronized void addB(){
b++;
}
}
Syncronized on the method declaration is syntactical sugar for this:
public void addA() {
syncronized (this) {
a++;
}
}
修饰静态方法,是类级别的同步
Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.
修饰某个对象
但是只能修饰引用。对于像 int 的原生型不能这样修饰。可以用 AtomicInteger。像这样
import java.util.concurrent.atomic.AtomicInteger;
class X {
AtomicInteger a;
AtomicInteger b;
public void addA() {
a.incrementAndGet();
}
public void addB() {
b.incrementAndGet();
}
}
网友评论