Java notes--About thread synchronization (5 ways to sync)

Source: Internet
Author: User
Tags modifier to domain

Transferred from: http://www.2cto.com/kf/201408/324061.html

Why use Sync?

    Java allows multithreading concurrency control, when multiple threads simultaneously manipulate a shareable resource variable (such as data additions and deletions),     will result in inaccurate data and conflict with each other. Therefore, a sync lock is added to avoid being called by other threads to,     to ensure that the variable is unique and accurate until the thread has completed the operation.    1. Synchronization methods      The method that has the Synchronized keyword modifier.      Because every object in Java has a built-in lock,,     built-in locks protect the entire method when the method is modified with this keyword. You need to get the built-in lock before calling the method, otherwise it will be in a blocking state.       code such as:     public synchronized void Save () {}      NOTE: The Synchronized keyword can also modify a static method, at which point the entire class    2 will be locked if the static method is called. Synchronizing code blocks      A statement block that has synchronized keyword adornments.      The statement block modified by this keyword is automatically added with a built-in lock for synchronization       code such as:     synchronized (object ) {    }      Note: Synchronization is a high-overhead operation, so you should minimize the content of synchronization.      There is usually no need to synchronize the entire method, using the synchronized code block to synchronize the key code.           code example:       copy code package com.xhj.thread;   & nbsp /**     * Use of thread synchronization      *      * @author xiehejun     *      */    public class Synchron Izedthread {         class Bank {             private int Acco UNT = 100;             public int getaccount () {          &NBS P     return account;           }            /* *             * with synchronization method              *   &N Bsp          * @param money             */      &NB Sp     public synchronized void Save (int money) {                Account + = money;           }            /**        &NBSP;    * with synchronous code block              *             &N bsp;* @param money             */            public void save1 (int money) {                synchronized (this) {                    account + + money;               }&NBSP ;          }       }         class Newthread Impleme NTS Runnable {            private Bank bank;             Public Newthread (Bank) {                This.bank = bank;           }             @Override             public void Run () {&nbsp               for (int i = 0; i < i++) {          &NBSP ;        //bank.save1 (Ten);                    BANK.S Ave (Ten);                    SYSTEM.OUT.PRINTLN (i + "account balance:" + Bank.getac Count ());               }           }        }        /**         * creating threads, calling internal classes     &NB Sp    */        public void Usethread () {            BANK Bank = New Bank ();            Newthread new_thread = new Newthread (Bank);      &NBSP ;     SYSTEM.OUT.PRINTLN ("Thread 1");            Thread thread1 = new Thread (new_thread);   &NBSp         Thread1.start ();            SYSTEM.OUT.PRINTLN ("Thread 2");  &N Bsp         Thread thread2 = new Thread (new_thread);            Thread2.star T ();       }         public static void main (string[] args) {    & nbsp       Synchronizedthread st = new Synchronizedthread ();            St.usethre AD ();       }    } copy code      3. Using special domain variables (volatile) for thread synchronization    & nbsp The A.volatile keyword provides a lock-free mechanism for access to domain variables,     B. Using a volatile modifier domain is equivalent to telling a virtual machine that the domain might be updated by another thread,     C. Therefore, each time the domain is used, it is recalculated instead of using the value in the Register      D.volatile does not provide any atomic operation, nor can it be used to modify the final type of variable           For example:         In the example above, it is possible to synchronize threads by simply adding a volatile modifier to the account.          code example:       Copy Code      //give only the code to be modified, the rest of the code with the same         class Bank {      &NBS P    //variables to be synchronized plus volatile            private volatile int account = 100;             public int getaccount () {                Retur N account;           }           //Here no longer need synchronized & nbsp           public void Save (int. money) {                AC Count + = money;           }       } copy code      NOTE: non-synchronous Q in multi-threading The problem is mainly in the reading and writing of the domain, if you let the domain itself avoid this issue, you do not need to modify the operation of the domain method.      With the final domain, locked-protected and volatile domains can avoid unsynchronized problems.      4. Thread synchronization using a re-enter lock      A new java.util.concurrent package is added to JavaSE5.0 to support synchronization.      Reentrantlock class is a re-entrant, mutual exclusion, implement lock interface, &NBSP;&NBsp   It has the same basic behavior and semantics as using the Synchronized method and fast, and extends its capabilities       Reenreantlock classes with:         Reentrantlock (): Create a Reentrantlock instance          lock (): Get lock      &NBSP ;   Unlock (): Release lock      NOTE: Reentrantlock () There is also a construction method that can create a fair lock, but it is not recommended to use the      & nbsp       For example:         based on the above example, the rewritten code is:              code example:       copy code//give only the code to be modified, the rest of the code with the         class Bank {                         private int account = 100;           //need to declare this lock             Private lock lock = new Reentrantloc K ();            public int getaccount () {              &N Bsp return account;          }           //There is no need synchronized       &NBS P     public void Save (int money) {                Lock.lock ();  &nbs P             try{                    Accoun T + = money;               }finally{            &NBS P       Lock.unlock ();               }        &N Bsp                  }       } copy code               NOTE: About the lock object and synchronized keyword selection:         A. It is best to use one of the two java.util.concurrent packages provided by the mechanism,             can help the user to handle all lock-related code.          B. If synchronizeThe D keyword can meet the needs of the user, just use synchronized, because it simplifies code          C. If more advanced functionality is required, use the Reentrantlock class, and be aware that the lock is released in a timely manner, otherwise a deadlock will occur, usually in the finally code release lock          5. Using local variables for thread synchronization      If you use threadlocal to manage variables, each thread that uses the variable gets a copy of the variable,     replicas are independent of each other. This allows each thread to arbitrarily modify its own copy of the variable without affecting other threads.        Common methods for ThreadLocal        ThreadLocal (): Creating a thread-local variable       Get (): Returns the value in the current thread copy of this thread's local variable      initialvalue (): Returns the "initial value" of the current thread for this thread's local variables      Set (T value): Sets the value in the current thread copy of this thread local variable to value       For example:         based on the above example, The modified code is:             Code instance:           copy code// Change the Bank class only, the rest of the code with the same         public class bank{           //Use threadlocal class to manage the total Enjoy variable account            private static threadlocal<integer> accOunt = new threadlocal<integer> () {                @Override     &NB Sp           protected Integer initialvalue () {              &NBSP ;     return 100;               }          &NBSP ; };            public void Save (int money) {              & nbsp Account.set (Account.get () +money);           }            Publ IC int getaccount () {                return Account.get ();      &NBS P    }       } copy code     NOTE: threadlocal and sync mechanism          A.thread Both local and synchronization mechanisms are designed to address the same variable access violation in multiple threads.          B. The former adopts a "space-for-time" approach, which uses "time-for-space" approaches

Java notes--About thread synchronization (5 ways to sync)

Related Article

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.