Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use AtomicIntegerFieldUpdater

Shulou Source: shulou.com Published: 2022-06-02 04:36:26 09月29日 Update

This article mainly explains "how to use AtomicIntegerFieldUpdater". 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 AtomicIntegerFieldUpdater.

AtomicXXXFieldUpdater is some fields that can be manipulated with non-thread-safe objects in a thread-safe manner. For example: 1000 people transfer one yuan to an account at the same time, then the cumulative increase should be 1000 yuan, in addition to lock and AtomicInteger can also be realized using FieldUpdater. Account class-BackAccountimport java.util.concurrent.atomic.AtomicIntegerFieldUpdater;public class BackAccount {private volatile int money; private static final AtomicIntegerFieldUpdater updater = AtomicIntegerFieldUpdater.newUpdater (BackAccount.class, "money"); BackAccount (int money) {this.money = money;} public void incMoney () {/ / manipulate fields updater.incrementAndGet (this) through AtomicIntegerFieldUpdater;} public int getMoney () {return money }} Task class-Taskpublic class Task implements Runnable {private BackAccount backAccount; Task (BackAccount account) {this.backAccount = account;} @ Override public void run () {backAccount.incMoney ();}} launch class import java.util.ArrayList;import java.util.List;public class Main {public static void main (String [] args) throws InterruptedException {BackAccount account = new BackAccount (0); List list = new ArrayList () For (int I = 0; I

< 1000 ; i++) { Thread t = new Thread(new Task(account)); list.add(t); t.start(); } for(Thread t : list) { t.join(); } System.out.println(account.getMoney()); }}运行结果

At this point, I believe you have a deeper understanding of "how to use AtomicIntegerFieldUpdater". 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!

Tags: Security content fields threads accounts learning practical deeper personal task interest at the same time practical practical object that is simple operation way method more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Redmi Microsoft Linux Apple