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 atomic operation class in Java multithreading

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you how to use the atomic operation class in Java multithreading, I believe most people do not know much about it, so share this article for your reference. I hope you will gain a lot after reading this article. Let's learn about it together.

Foreword:

After java5, we have come into contact with the atomic operation of threads, that is, when we modify it, we only need to ensure that it is safe at that moment, and we can deal with the concurrent modification of objects after the corresponding wrapper. This article summarizes the usage of Atomic series classes, including:

1. Basic types use public class AtomicTest {/ * list of common methods * * @ see AtomicInteger#get () directly return value * @ see AtomicInteger#getAndAdd (int) to increase specified data, return pre-change data * @ see AtomicInteger#getAndDecrement () decrease by 1, return pre-reduced data * @ see AtomicInteger#getAndIncrement () increase by 1 Return the data before the increase * @ see AtomicInteger#getAndSet (int) set the specified data, return the data before the setting * @ see AtomicInteger#addAndGet (int) after increasing the specified data, return the increased data * @ see AtomicInteger#decrementAndGet () decrease by 1, return the reduced value * @ see AtomicInteger#incrementAndGet () increase by 1 Return the increased value * @ see AtomicInteger#lazySet (int) set * @ see AtomicInteger#compareAndSet (int, int) only when get is attempted. If the increase is successful, return true otherwise return false * * / public static void main (String [] args) {final AtomicTicket ticket = new AtomicTicket () For (int I = 0; I

< 3; i++) { new Thread(new Runnable() { @Override public void run() { while (ticket.getCount() >

0) {System.out.println (Thread.currentThread (). GetName () + "count:" + ticket.decrement ());}) .start ();}} class AtomicTicket {public AtomicInteger count = new AtomicInteger (100); public int decrement () {return count.getAndDecrement () } public int getCount () {return count.get ();}}

Thread-0 count: 100

Thread-2 count: 98

Thread-1 count: 99

Thread-2 count: 96

Thread-0 count: 97

Thread-2 count: 94

Thread-2 count: 92

Thread-1 count: 95

Omit in the middle.

Thread-1 count: 12

Thread-2 count: 7

Thread-0 count: 9

Thread-2 count: 5

Thread-1 count: 6

Thread-2 count: 3

Thread-0 count: 4

Thread-2 count: 1

Thread-1 count: 2

two。 Array type uses public class AtomicIntegerArrayTest {/ * common method list * @ see AtomicIntegerArray#addAndGet (int, int) to perform addition. The first parameter is the subscript of the array, the second parameter is the increased number, and the increased result is returned * @ see AtomicIntegerArray#compareAndSet (int, int, int) comparison modification. Parameter 1: array subscript, parameter 2: original value, parameter 3, modify target value. If the modification succeeds, return true otherwise the false * @ see AtomicIntegerArray#decrementAndGet (int) parameter is the array subscript, reduce the array corresponding number by 1, return the reduced data * @ see AtomicIntegerArray#incrementAndGet (int) parameter is the array subscript, increase the array corresponding number by 1, and return the increased data * * @ see AtomicIntegerArray#getAndAdd (int, int) is similar to addAndGet. The difference is that the return value is the data before the change * @ see AtomicIntegerArray#getAndDecrement (int) is similar to decrementAndGet, the difference is that the data before the change is returned * @ see AtomicIntegerArray#getAndIncrement (int) is similar to incrementAndGet, the difference is that the data before the change is returned * @ see AtomicIntegerArray#getAndSet (int, int), the corresponding subscript number is set to the specified value, and the second parameter is the set value The data returned is the data before the change * / private final static AtomicIntegerArray ATOMIC_INTEGER_ARRAY = new AtomicIntegerArray (new int [] {1, 2, 4, 5, 6, 7, 8, 9, 10}) Public static void main (String [] args) throws InterruptedException {Thread [] threads = new Thread [10]; for (int I = 0; I

< 10 ; i++) { final int index = i; threads[i] = new Thread() { public void run() { int original = ATOMIC_INTEGER_ARRAY.get(index); int result = ATOMIC_INTEGER_ARRAY.addAndGet(index, index + 1); System.out.println("currentThread:" + Thread.currentThread().getName() + " , 原始值为:" + original + ",增加后的结果为:" + result); } }; threads[i].start(); } for(Thread thread : threads) { thread.join(); } System.out.println("=========================>

\ nThe execution has been completed, and the list of results: "); for (int I = 0; I)

< ATOMIC_INTEGER_ARRAY.length() ; i++) { System.out.println(ATOMIC_INTEGER_ARRAY.get(i)); } }} currentThread:Thread-0 , 原始值为:1,增加后的结果为:2 currentThread:Thread-3 , 原始值为:4,增加后的结果为:8 currentThread:Thread-2 , 原始值为:3,增加后的结果为:6 currentThread:Thread-1 , 原始值为:2,增加后的结果为:4 currentThread:Thread-5 , 原始值为:6,增加后的结果为:12 currentThread:Thread-4 , 原始值为:5,增加后的结果为:10 currentThread:Thread-6 , 原始值为:7,增加后的结果为:14 currentThread:Thread-7 , 原始值为:8,增加后的结果为:16 currentThread:Thread-8 , 原始值为:9,增加后的结果为:18 currentThread:Thread-9 , 原始值为:10,增加后的结果为:20 =========================>

Execution has been completed, list of results:

two

four

six

eight

ten

twelve

fourteen

sixteen

eighteen

twenty

3. Use of reference types

Public class AtomicReferenceTest {public static void main (String [] args) {People people1 = new People ("Bom", 0); People people2 = new People ("Tom", 10); / / initialize a value first. If not initialized, the default value is null AtomicReference reference = new AtomicReference (people1); People people3 = reference.get () If (people3.equals (people1)) {System.out.println ("people3:" + people3);} else {System.out.println ("else:" + people3) } / * current value: compare the current value with the value obtained by reference.get (). If equal, true and update the value to the expected value * expected value: update to the expected value if true is returned, and do not update the value if false is returned * / boolean b = reference.compareAndSet (null, people2) System.out.println ("myClass.main-" + b + "- -" + reference.get ()); boolean b1 = reference.compareAndSet (people1, people2); System.out.println ("myClass.main-" + b1 + "- -" + reference.get ()); new Thread (new Runnable () {@ Override public void run () {System.out.println (Thread.currentThread (). GetName () People people = reference.get (); people.setName ("Tom" + Thread.currentThread (). GetName ()); people.setAge (people.getAge () + 1); reference.getAndSet (people); System.out.println (Thread.currentThread (). GetName () + reference.get (). ToString ();}}) .start () New Thread (new Runnable () {@ Override public void run () {System.out.println (Thread.currentThread (). GetName ()); People people = reference.get (); people.setName ("Tom" + Thread.currentThread (). GetName ()); people.setAge (people.getAge () + 4) Reference.getAndSet (people); System.out.println (Thread.currentThread (). GetName () + reference.get (). ToString ();}}) .start ();}} class People {private String name; private int age; public People (String name, int age) {this.name = name; this.age = age } public String getName () {return name;} public void setName (String name) {this.name = name;} public int getAge () {return age;} public void setAge (int age) {this.age = age } @ Override public String toString () {return "People {" + "name='" + name +''+ ", age=" + age +'}';}} 4. Field types using public class AtomicIntegerFieldUpdaterTest {/ * can directly access the corresponding variables, modify and handle * conditions: in the accessible area, if the private or satchel access default type and non-parent class protected cannot be accessed * secondly, the access object cannot be a variable of static type (because it cannot be calculated when calculating the offset of the attribute) Nor can it be a variable of type final (because it cannot be modified at all), it must be an ordinary member variable *

* method (description is almost the same as that of AtomicInteger The only difference is that the first parameter requires passing a reference to the object) * * @ see AtomicIntegerFieldUpdater#addAndGet (Object, int) * @ see AtomicIntegerFieldUpdater#compareAndSet (Object, int, int) * @ see AtomicIntegerFieldUpdater#decrementAndGet (Object) * @ see AtomicIntegerFieldUpdater#incrementAndGet (Object) * @ see AtomicIntegerFieldUpdater#getAndAdd (Object) Int) * @ see AtomicIntegerFieldUpdater#getAndDecrement (Object) * @ see AtomicIntegerFieldUpdater#getAndIncrement (Object) * @ see AtomicIntegerFieldUpdater#getAndSet (Object, int) * / public final static AtomicIntegerFieldUpdater ATOMIC_INTEGER_UPDATER = AtomicIntegerFieldUpdater.newUpdater (A.class, "intValue") Public static void main (String [] args) {final An a = new A (); for (int I = 0; I < 10; iTunes +) {new Thread () {public void run () {System.out.println (Thread.currentThread (). GetName () + "+ ATOMIC_INTEGER_UPDATER.get (a)) ATOMIC_INTEGER_UPDATER.addAndGet (a, 11); System.out.println (Thread.currentThread (). GetName () + "+ ATOMIC_INTEGER_UPDATER.get (a)) If (ATOMIC_INTEGER_UPDATER.compareAndSet (a, ATOMIC_INTEGER_UPDATER.get (a), 120) {System.out.println (Thread.currentThread (). GetName () + "the corresponding value has been modified!") ;} System.out.println (Thread.currentThread (). GetName () + "+ ATOMIC_INTEGER_UPDATER.get (a));}. Start ();}} static class A {volatile int intValue = 100;}}

Thread-0 100

Thread-2 100

Thread-1 100

Thread-2 122

Thread-3 111

Thread-5 120

Thread-0 111

Thread-5 142

Thread-3 131

The corresponding value of Thread-2 has been modified!

Thread-2 120

Thread-8 120

Thread-4 133

Thread-1 133

Thread-9 142

Thread-4 142

The corresponding value of Thread-4 has been modified!

Thread-8 131

The corresponding value of Thread-3 has been modified!

Thread-3 120

Thread-7 120

Thread-7 131

The corresponding value of Thread-5 has been modified!

Thread-5 120

Thread-6 120

The corresponding value of Thread-0 has been modified!

Thread-6 131

The corresponding value of Thread-7 has been modified!

The corresponding value of Thread-8 has been modified!

Thread-4 120

Thread-9 131

The corresponding value of Thread-1 has been modified!

The corresponding value of Thread-9 has been modified!

Thread-8 120

Thread-7 120

The corresponding value of Thread-6 has been modified!

Thread-0 131

Thread-6 120

Thread-9 120

Thread-1 120

These are all the contents of this article entitled "how to use atomic operation classes in Java multithreading". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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