Java Atomic weight Atomic example (Atomicreference)

Source: Internet
Author: User

The Java Concurrency Library provides a number of atomic classes to support data security for concurrent access, in addition to commonly used

Atomicinteger, Atomicboolean, Atomiclong and beyond.
atomicreference An atomic operation used to support an object:atomicreference<v> can encapsulate a reference to a V instance by
Public
Can support concurrent access, set when the comparison to judge, if the current value and the same as before the return false, otherwise the data does not change, such as the following code
The concurrency count is implemented using Atomicreference:
Package test;import Java.util.concurrent.countdownlatch;import java.util.concurrent.atomic.AtomicReference; Public classTS { Public Static voidMain (string[] args) throws Interruptedexception {dfasd111 (); }    Private StaticAtomicreference<integer> AR =NewAtomicreference<integer> (0);  Public Static voiddfasd111 () throws Interruptedexception {intt = -; Finalintc = -; Final Countdownlatch latch=NewCountdownlatch (t);  for(inti =0; I < T; i++) {            NewThread (NewRunnable () {@Override Public voidrun () { for(inti =0; I < C; i++) {                         while(true) {Integer temp= Ar.Get(); if(Ar.compareandset (temp, temp +1)) {                                 Break;                }}} latch.countdown ();        }}). Start (); } latch.await(); System. out. println (AR.Get());//10000000    }     PublicFinalvoidTest () {System. out. println ( This. GetClass ()); }}
One, the atomic weight to achieve the counter
Import Java.util.hashset;import Java.util.set;import java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.atomic.AtomicInteger; Public classAtomiccounter {PrivateAtomicinteger value =NewAtomicinteger ();  Public intGetValue () {returnValue.Get(); }     Public intIncrease () {returnValue.incrementandget ();//internal use of the Dead loop for (;;) Call Compareandset (current, next)//return value.getandincrement ();    }     Public intIncrease (inti) {returnValue.addandget (i);//internal use of the Dead loop for (;;) Call Compareandset (current, next)//return Value.getandadd (i);    }     Public intdecrease () {returnValue.decrementandget ();//internal use of the Dead loop for (;;) Call Compareandset (current, next)//return value.getanddecrement ();    }     Public intDecrease (inti) {returnValue.addandget (-i);//internal use of the Dead loop for (;;) Call Compareandset (current, next)//return Value.addandget (-i);    }     Public Static voidMain (string[] args) {Final Atomiccounter counter=NewAtomiccounter (); Executorservice Service=Executors.newcachedthreadpool ();  for(inti =0; I <Ten; i++) {Service.execute (NewRunnable () {@Override Public voidrun () {System. out. println (Counter.increase ());        }            });    } service.shutdown (); }}

Second, the atomic weight of the realization of bank withdrawals

import Java.util.random;import Java.util.concurrent.executorservice;import java.util.concurrent.Executors; Import Java.util.concurrent.atomic.AtomicLong; Public classAccount {PrivateAtomiclong balance;  PublicAccount (LongMoney ) {Balance=NewAtomiclong (Money); System. out. println ("Total Money:"+balance); }     Public voidDepositLongMoney )    {Balance.addandget (money); }     Public voidWithdraw (LongMoney ) {         for(; ; ) {//To ensure that the same time someone also in the withdrawal can also try to withdraw money, if you do not need to try to withdraw money, you can remove this sentence            LongOldValue = balance.Get(); if(OldValue <Money ) {System. out. println (Thread.CurrentThread (). GetName () +"Insufficient balance! Balance:"+balance);  Break; }            Try{Thread.Sleep (NewRandom (). Nextint ( +));}Catch(Exception e) { }//Simulated withdrawal time            if(Balance.compareandset (OldValue, OldValue-Money )) {System. out. println (Thread.CurrentThread (). GetName () +"Withdrawals"+ Money +"Success! Balance:"+balance);  Break; } System. out. println (Thread.CurrentThread (). GetName () +"encounter concurrency and try to withdraw again! "); }    }     Public Static voidMain (string[] args) {Final account account=NewAccount ( +); Executorservice Pool=Executors.newcachedthreadpool (); inti =0;  while(I++ < -) {Pool.execute (NewRunnable () {@Override Public voidrun () {Account.withdraw ( -);        }            });    } pool.shutdown (); }}



Java Atomic weight Atomic example (Atomicreference)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.