首先说一下在Java中什么是原子类
- 我门把 高中化学中的原子类分开。在Java中原子操作是:原子操作:一个或多个操作在CPU执行过程中不被中断的特性
线程中的锁和原子类有什么区别呢
- 怎么说呢!他们都可以保证线程安全操作。区别在于锁的粒度。例如Lock锁,锁的都是代码块,或者方法。synchronized 可以锁代码块、类、方法。而原子类锁的粒度更细,它可以锁一个变量。锁数组、锁对象。
原子类在Java中的包路径
java.util.concurrent.atomic
你说可以锁变量,那有那些呢?
AtomicBoolean
AtomicInteger
AtomicLong
锁数组
AtomicIntegerArray
AtomicLongArray
AtomicReferenceArray
对非线程安全的变量,升级为原子安全类
AtomicIntegerFieldUpdater
AtomicLongFieldUpdater
AtomicReferenceFieldUpdater
其实还有增加原子类
DoubleAdder
LongAdder
怎么说呢!我们比较常用的也没几个:今天我们就先介绍一下AtomicInteger
方法名 | 方法说明 |
---|
get() | 获取当前变量值 |
set(int newValue) | 设置为给定值 |
getAndSet(int newValue) | 以原子方式设置为给定值并返回旧值 |
compareAndSet(int expect, int update) | 如果当前值==预期值,则自动将值设置为给定的更新值 |
getAndIncrement() | 以原子方式将当前值加一。 |
getAndDecrement() | 以原子方式将当前值减一 |
incrementAndGet() | 以原子方式将当前值加一 |
decrementAndGet() | 以原子方式将当前值减一 |
简单给大家写一个测试类:
public class Int {
private static AtomicInteger atomicInteger = new AtomicInteger();
private static volatile int i;
public static void main(String[] args) throws InterruptedException {
Int anInt = new Int();
Thread thread = new Thread(() -> {
anInt.test();
});
Thread thread1 = new Thread(() -> {
anInt.test();
});
thread.start();
thread1.start();
thread1.join();
thread.join();
System.out.println("原子int 加加结果:"+atomicInteger.get());
System.out.println("没有原子操作的i:"+ i);
}
private void test() {
for (int j = 0, size = 1000; j < size; j++) {
atomicInteger.getAndIncrement();
i++;
}
}
}
效果图:
下一篇给大家写一篇。引用属性的升级原子性操作