在 java.util.concurrent.atomic包下的类,在单个变量操作是支持原子操作的。其中的类有get和set方法和volatile
变量的read和write方法一样,然而,一个set方法和随后的get方法在操作同一个变量的时候有一种happens-before关系原子的compareAndSet方法保证了内存的一致性的特性,然而在做一些简单的算术操作应用于integer原子变量。
看一些这个包是怎么使用的,使用原始的方法来干扰线程
class Counter {
private int c = 0;
public void increment() {
c++;
}
public void decrement() {
c--;
}
public int value() {
return c;
}
}
一种方式可以是Counter类多线程使用时变安全,就是使用synchronized来同步方法,也是在同步计数器中
class SynchronizedCounter {
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
}
}
对于这个简单的类,同步是一个可接受的方法,但是对于一个
比较复杂的类,我们可能想避免不必要的同步活动
的影响。
使用AtomicInteger来替换int字段允许我们防止线程不需要同步干扰,在AtomicCounter
import java.util.concurrent.atomic.AtomicInteger;
class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0);
public void increment() {
c.incrementAndGet();
}
public void decrement() {
c.decrementAndGet();
}
public int value() {
return c.get();
}
}
原文地址:http://docs.oracle.com/javase/tutorial/essential/concurrency/atomicvars.html
3842

被折叠的 条评论
为什么被折叠?



