为了提高性能,不一定要锁定this,例如,sharedresource有两个独立变化的变量:
public class sharedresouce {
private int a = 0;
private int b = 0;
public synchronized void seta(int a) { this.a = a; }
public synchronized void setb(int b) { this.b = b; }
}
若同步整个方法,则seta()的时候无法setb(),setb()时无法seta()。为了提高性能,可以使用不同对象的锁:
private object sync_a = new object();
private object sync_b = new object();
public void seta(int a) {
synchronized(sync_a) {
this.a = a;
}
}
public synchronized void setb(int b) {
synchronized(sync_b) {
this.b = b;