About atomic operations in Java Multi-threading

Source: Internet
Author: User

Various situations ensure the correctness and completeness of the data.

 Public classTestmultithreadImplementsRunnable {Private Static inti; Private Static volatileInteger VI = 0; Private StaticAtomicinteger ai =NewAtomicinteger (); Private StaticInteger si = 0; Private StaticInteger ia = 1; Private Static intRI; Private StaticAtomicinteger flag =NewAtomicinteger (); Private StaticLock lock =NewReentrantlock ();//If lock does not add the static keyword, then each thread will be locked to a specific object,//rather than this class. The data is not correct.@Override Public voidrun () { for(intk = 0; K < 200000; k++) {i++;//is not an atomic operation, there are three steps (get the value of I, i+1, the result of i+1 after assigning to i) results will be abnormal. When a thread executes to i+1, it has not yet been assigned, and the other line i+1 and assigns the value. vi++;//Ibid., ② explanationAi.incrementandget ();//an int value that can be updated atomically.                    Atomically adds 1 to the current value. It has only one step, which is the only step in any thread execution. //synchronized (SI) {//This method does not take the value of SI, it is the object that should be locked for the synchronization statement, use integer as the object lock, which in itself does not have any problems. //si++; //but the operation in the synchronous body is to change the current lock object, the result is that the former object lock has actually changed, not for the only one object lock, so there will be problems. //Therefore, a change to a common object can solve the problem. //there is actually an assignment operation in the + + operation, when the object has changed, or is non-atomic operation// }            synchronized(IA) {//using the immutable IA as the lock object can guarantee the correctness of the datasi++;   } lock.lock (); //the lock lock must be a static            Try{ri++; } finally{lock.unlock ();    }} flag.incrementandget (); }     Public Static voidMain (string[] args)throwsinterruptedexception {testmultithread T1=NewTestmultithread (); Testmultithread T2=NewTestmultithread (); Executorservice EXEC1=Executors.newcachedthreadpool (); Executorservice EXEC2=Executors.newcachedthreadpool ();        Exec1.execute (t1);        Exec2.execute (T2);  while(true) {            if(Flag.intvalue () = = 2) {System.out.println ("I>>>>>" +i); System.out.println ("Vi>>>>>" +VI); System.out.println ("Ai>>>>>" +AI); System.out.println ("Si>>>>>" +si); System.out.println ("Ri>>>>>" +RI);  Break; } thread.sleep (50); }    }}

Results:

i>>>>>398950
vi>>>>>386295
ai>>>>>400000
si>>>>>400000
ri>>>>>400000

Explanation ②:

In the Java garbage collection article, the allocation of memory at runtime of the JVM is described. One of the memory areas is the JVM virtual machine stack, and each thread runs with a line stacks,

Line stacks saves the variable value information when the thread runs. When a thread accesses an object, the value of the variable that corresponds to the heap memory is first found by the object's reference, and then the heap memory

The specific value of the variable is load into the thread's local memory, a copy of the variable is created, and then the thread is no longer related to the object in the heap memory variable value, but directly modifies the value of the replica variable.

At some point after the modification (before the thread exits), the value of the thread variable copy is automatically written back to the object in the heap variable. This changes the value of the object in the heap.

About atomic operations in Java Multi-threading

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.