修飾成員方法逛球,是對象級別的同步
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++;
}
}
修飾靜態(tài)方法千元,是類級別的同步
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();
}
}