How to use AtomicReference
This article mainly explains "how to use AtomicReference". Friends who are interested might as well take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use AtomicReference.
AtomicReference atomic update object reference example: 1000 threads add 1 to an Integer until 1000 starts the file package com.jane;import java.util.ArrayList;import java.util.List;import java.util.concurrent.atomic.AtomicReference;public class Main {public static void main (String [] args) throws InterruptedException {AtomicReference ref = new AtomicReference (new Integer (0)); List list = new ArrayList (); for (int I = 0; I
< 1000; i++) { Thread t = new Thread(new Task(ref), "Thread-no" + i); list.add(t); t.start(); } for (Thread t : list) { t.join(); } System.out.println(ref.get()); // 打印2000 }}Task任务package com.jane;import java.util.concurrent.atomic.AtomicReference;public class Task implements Runnable { private AtomicReference ref; Task(AtomicReference ref) { this.ref = ref; } @Override public void run() { for (; ; ) { //自旋操作 Integer oldV = ref.get(); if (ref.compareAndSet(oldV, oldV + 1)) // CAS操作 break; } }}结果
Indicates that AtomicReference holds an object reference to volatile
Using the CAS principle of unsafe to realize the lock-free operation on the reference object
At this point, I believe you have a deeper understanding of "how to use AtomicReference". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!