Java voliate, synchronized, Atomicinteger use

Source: Internet
Author: User

1:voliate

  Used in multi-threading, synchronous variables. thread to improve efficiency, the member variable (such as a) a Copies a copy (such as B), and the access to a in the thread actually accesses B. Synchronization of A and B occurs only in certain actions. Thus there is a and B inconsistency. Volatile is used to avoid this situation. Volatile tells Jvm, 

Public class counter {    public volatile  static int  count = 0;    public static void inc ()  {         //here is delayed by 5 milliseconds, making the result obvious         try {             thread.sleep (5);         } catch  (interruptedexception e)  {         }        //synchronized (Counter.class)  {         count ++;         }    }     public static void main (String[]  args)  throws InterruptedException {     final  Countdownlatch latch = nEw countdownlatch (+);         //start 1000 threads at the same time to perform i++ calculations to see actual results         for  (int i = 0; i < 1000 ;  i++)  {            new thread (new  runnable ()  {                  @Override                  public void run ()  {                     counter.inc ();                     latch.countdown ();                 }             }). Start ();        }         latch.await ();         //the value of each run here may be different, possibly 1000 &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Run Result: counter.count="  +  Counter.count);     }}

you can see that the result of the run: counter.count=929 (number random), but if you comment out the sync block synchronized Open, the console output is

2.synchronized

It is used to modify a method or a block of code to ensure that at most one thread executes the code at the same time.

First, when two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.

Second, however, when a thread accesses one synchronized (this) of an object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in the object.

Third, in particular, when a thread accesses one synchronized (this) of an object to synchronize a block of code, other threads will block access to all other synchronized (this) synchronization blocks in object.

The third example also applies to other synchronous blocks of code. That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains the object lock of the objects. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.

The above rules apply to other object locks as well.

3:atomicinteger

using Atomicinteger, even without synchronization block synchronized, the final result is 1000, can see the role of Atomicinteger, with an int value that is updated atomically. It is mainly used for efficient program processing in high concurrency environments. Use a non-blocking algorithm to implement concurrency control.

Public class counter {   public  static atomicinteger count  = new atomicinteger (0);     public static void inc ()  { The          //is delayed by 1 milliseconds, making the result obvious          try {            thread.sleep (1);         } catch  (interruptedexception e)  {         }         Count.getandincrement ();     }     public static void  main (String[] args)  throws InterruptedException {         final countdownlatch latch = new countdownlatch (;  )       //simultaneous boot 1000threads, go for i++ calculations, see actual results         for  (int i = 0; i  < 1000; i++)  {             New thread (new runnable ()  {                  @Override                  public void run ()  {                     counter.inc ();                      Latch.countdown ();                 }            }). Start ();         }&nbSp;       latch.await ();         // The value of each run here may be different, possibly 1000        system.out.println ("Run Result: counter.count=")  + counter.count);     }}


Java voliate, synchronized, Atomicinteger use

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.