Java 中的原子操作
1、 java.util.concurrent.atomic包下
2、 线程原子性操作:AtomicInteger 作为成员变量使用
3、 分类:原子更新基本类型、原子更新数组类型、原子更新引用类型、原子更新属性类型
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest {
private static AtomicInteger atomicInteger = new AtomicInteger();
public static void main(String[] args) {
new Thread(() -> {
for (int i = 0; i < 100; i++) {
//System.out.println(atomicInteger.getAndIncrement());
System.out.println(atomicInteger.incrementAndGet());
}
}).start();
}
}
public class User {
private String userName;
private int age;
public User(String userName, int age) {
this.userName = userName;
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", age=" + age +
'}';
}
}
import java.util.concurrent.atomic.AtomicReference;
public class AtomicReferenceTest {
public static AtomicReference<User> atomicReference = new AtomicReference<>();
public static void main(String[] args) {
User user = new User("ellen", 25);
atomicReference.set(user);
User updateUser = new User("json", 26);
atomicReference.compareAndSet(user, updateUser);
System.out.println(user);
System.out.println(atomicReference.get().getUserName());
System.out.println(atomicReference.get().getAge());
}
}