Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use AtomicReference

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report