您的位置:首页 > Web前端

高并发编程之AtomicReferenceArray讲解

2019-02-21 22:32 120 查看

一、AtomicReferenceArray介绍
AtomicReferenceArray类提供了可以原子读取和写入的底层引用数组的操作,并且还包含高级原子操作。 AtomicReferenceArray支持对底层引用数组变量的原子操作。 它具有获取和设置方法,如在变量上的读取和写入。 也就是说,一个集合与同一变量上的任何后续获取相关联。

二、AtomicReferenceArray几个常用的方法代码实例
①、创建给定长度的新 AtomicReferenceArray。

package chapter3.atomicreferencearray;

import java.util.concurrent.atomic.AtomicReferenceArray;

/**
* @author czd
*/
public class AtomicReferenceArrayTest {
public static void main(String[] args) {
//1、创建给定长度的新 AtomicReferenceArray。
AtomicReferenceArray<Integer> atomicReferenceArray = new AtomicReferenceArray<>(10);
//2、set:将位置 i 的元素设置为给定值。
atomicReferenceArray.set(1,5);
System.out.println("Vaule: " + atomicReferenceArray.get(1));
}
}

②、compareAndSet()方法:如果当前值 == 预期值,则以原子方式将位置 i 的元素设置为给定的更新值。

package chapter3.atomicreferencearray;

import java.util.concurrent.atomic.AtomicReferenceArray;

/**
* @author czd
*/
public class AtomicReferenceArrayTest {
public static void main(String[] args) {
//3、如果当前值 == 预期值,则以原子方式将位置 i 的元素设置为给定的更新值。
AtomicReferenceArray<Integer> atomicReferenceArray1 = new AtomicReferenceArray<>(10);
atomicReferenceArray1.set(2,10);
System.out.println("Value: " + atomicReferenceArray1.get(2));
boolean bool = atomicReferenceArray1.compareAndSet(2,10,20);
System.out.println("是否预期值与当前值相等:" + bool);
System.out.println("Value: " + atomicReferenceArray1.get(2));
}
}

③、length()方法:返回该数组的长度。

package chapter3.atomicreferencearray;

import java.util.concurrent.atomic.AtomicReferenceArray;

/**
* @author czd
*/
public class AtomicReferenceArrayTest {
public static void main(String[] args) {
//4、返回该数组的长度。
AtomicReferenceArray<Integer> atomicReferenceArray2 = new AtomicReferenceArray<>(10);
System.out.println("数组长度:" + atomicReferenceArray2.length());
}
}

④、getAndSet()方法:获取当前索引的值,再将此索引设置新的值

package chapter3.atomicreferencearray;

import java.util.concurrent.atomic.AtomicReferenceArray;

/**
* @author czd
*/
public class AtomicReferenceArrayTest {
public static void main(String[] args) {
//5、获取当前索引的值,再将此索引设置新的值
AtomicReferenceArray<Integer> atomicReferenceArray3 = new AtomicReferenceArray<>(10);
atomicReferenceArray3.set(2,10);
System.out.println("旧值:" + atomicReferenceArray3.get(2));
Integer result = atomicReferenceArray3.getAndSet(2,50);
System.out.println("获取的result值:" + result);
System.out.println("新值:" + atomicReferenceArray3.get(2));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: