有几种同步对静态变量的访问的方法。
使用同步静态方法。这将在类对象上同步。
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是最好的,因为锁对象没有暴露在类之外。



