3 回答

TA貢獻(xiàn)1934條經(jīng)驗(yàn) 獲得超2個(gè)贊
有幾種同步對(duì)靜態(tài)變量的訪問(wèn)的方法。
使用同步靜態(tài)方法。這將在類對(duì)象上同步。
public class Test {
private static int count = 0;
public static synchronized void incrementCount() {
count++;
}
}
在類對(duì)象上顯式同步。
public class Test {
private static int count = 0;
public void incrementCount() {
synchronized (Test.class) {
count++;
}
}
}
在其他靜態(tài)對(duì)象上同步。
public class Test {
private static int count = 0;
private static final Object countLock = new Object();
public void incrementCount() {
synchronized (countLock) {
count++;
}
}
}
在很多情況下,方法3是最好的,因?yàn)殒i對(duì)象沒(méi)有暴露在類之外。

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
如果您只是共享一個(gè)計(jì)數(shù)器,請(qǐng)考慮使用AtomicInteger或java.util.concurrent.atomic包中的另一個(gè)合適的類:
public class Test {
private final static AtomicInteger count = new AtomicInteger(0);
public void foo() {
count.incrementAndGet();
}
}
添加回答
舉報(bào)