在java.util.concurrent.atomic包中,提供了原子变量,这里面的所有原子变量都提供了set和get方法。这些变量可以保证“happens-before”的关系。
1.非线程安全的
class Counter {
private int c = 0;
public void increment() {
c++;
}
public void decrement() {
c--;
}
public int value() {
return c;
}
}
2.线程安全的,使用同步方法
class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
3.线程安全的,使用原子变量
class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0);
public void increment() {
c.incrementAndGet();
}
public void decrement() {
c.decrementAndGet();
}
public int value() {
return c.get();
}
}