After learning this chapter, the reader needs to answer:
1. What is CAS?
2. What is the ABA? How to solve THE ABA problem?
3. In what scenarios are atomic references used?
6.4.1 What is CAS
CAS is short for CompareAndSwap, used for comparison and exchange.
When a thread reads and assigns values to a variable, it must first copy the variable from the main memory to the working memory of its own thread, and then write the variable back to the main memory after the operation is completed
package com.javaliao.backstage; import java.util.concurrent.atomic.AtomicInteger; Public class Demo {public static void main(String[] args) {public static void main(String[] args) { The default initial value is 0 AtomicInteger AtomicInteger = new AtomicInteger(5); // When the working memory of the thread is written back to the main memory, the first parameter is taken as the expected value and the main memory value is compared, if the expected value and the main memory value are the same, 5, Update values in the main memory is 2019 System. Out. The println (atomicInteger.com pareAndSet (5, 2019) + "\ t:" + atomicInteger. The get ()); // thread a new ThreCopy the code