Java在原子操作上同步

L4z*_*4zy 1 java multithreading synchronization

这个Java类线程是安全的还是重置方法也需要同步?如果有,有人可以告诉我原因吗?

public class NamedCounter {
   private int count;
   public synchronized void increment() { count++; }
   public synchronized int getCount() { return count; }
   public void reset() { count = 0; }
}
Run Code Online (Sandbox Code Playgroud)

Mul*_*der 8

并非没有同步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
}
Run Code Online (Sandbox Code Playgroud)

要解决上述问题,你需要这样的东西

NamedCounter counter = new NamedCounter();
if(counter.incrementAndGet()== 1) { //incrementAndGet() must be a synchronized method
    //do something....now it is thread safe
}
Run Code Online (Sandbox Code Playgroud)

相反,使用Java的bulit-in类AtomicInteger,它涵盖了所有情况.或者,如果您正在尝试学习线程安全性,那么请使用AtomicInteger作为标准(学习).

对于生产代码,请使用AtomicInteger,甚至不要三思而后行!请注意,使用AtomicInteger不会自动保证代码中的线程安全.您必须使用api提供的方法.他们是有原因的.