3 回答

TA贡献1934条经验 获得超2个赞
有几种同步对静态变量的访问的方法。
使用同步静态方法。这将在类对象上同步。
public class Test {
private static int count = 0;
public static synchronized void incrementCount() {
count++;
}
}
在类对象上显式同步。
public class Test {
private static int count = 0;
public void incrementCount() {
synchronized (Test.class) {
count++;
}
}
}
在其他静态对象上同步。
public class Test {
private static int count = 0;
private static final Object countLock = new Object();
public void incrementCount() {
synchronized (countLock) {
count++;
}
}
}
在很多情况下,方法3是最好的,因为锁对象没有暴露在类之外。

TA贡献1853条经验 获得超18个赞
如果您只是共享一个计数器,请考虑使用AtomicInteger或java.util.concurrent.atomic包中的另一个合适的类:
public class Test {
private final static AtomicInteger count = new AtomicInteger(0);
public void foo() {
count.incrementAndGet();
}
}
添加回答
举报