不是沒有同步rest()和添加更多的方法。你會遇到你需要更多方法的情況。例如
NamedCounter counter = new NamedCounter();
counter.increment();
// at this exact time (before reaching the below line) another thread might change changed the value of counter!!!!
if(counter.getCount() == 1) {
//do something....this is not thread safe since you depeneded on a value that might have been changed by another thread
}
要解決上面你需要像
NamedCounter counter = new NamedCounter();
if(counter.incrementAndGet()== 1) { //incrementAndGet() must be a synchronized method
//do something....now it is thread safe
}
相反,使用Java的儲存卡,在課堂上的AtomicInteger涵蓋所有情況。或者如果你正在嘗試學習線程安全性,那麼使用AtomicInteger作爲標準(從中學習)。
對於產品代碼,無需考慮兩次就可以與AtomicInteger一起使用!請注意,使用AtomicInteger不會自動保證代碼中的線程安全。你必須使用api提供的方法。他們在那裏是有原因的。
如果不知道所需的語義,就無法回答這個問題。你有什麼保證,如果有的話? –
你爲什麼不使用[** AtomicInteger **](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicInteger.html)? – jlordo