Java Thread (1)-Thread synchronization

Source: Internet
Author: User

Java provides two ways to create a thread:

    • By implementing the Runable interface;
    • By inheriting the thread class itself.

Thread synchronization

Why use synchronization? Java allows multithreading concurrency control, when multiple threads concurrently manipulate a shareable resource variable (such as data additions and deletions), will result in inaccurate data and conflict with each other, so join a synchronization lock to avoid being called by another thread until the thread has completed the operation. Thus, the uniqueness and accuracy of the variable are ensured.5 Modes of synchronization1, the synchronization method is synchronized keyword modification method. Because each object in Java has a built-in lock, the built-in lock protects the entire method when the method is decorated with this keyword. You need to get the built-in lock before calling the method, otherwise it will be in a blocking state.     Note: The Synchronized keyword can also be used to modify a static method, if the static method is called, the entire class 2 is locked, and the synchronous code block is a block of statements with the Synchronized keyword adornment. Statement blocks that are decorated with this keyword are automatically added with built-in locks for synchronization
Synchronized (object) {     }
Note: Synchronization is a high-overhead operation, so you should minimize the content of synchronization. It is usually not necessary to synchronize the entire method, using the synchronized code block to synchronize the key code.
1  PackageCom.xhj.thread;2  3     /**4 * Application of thread synchronization5      * 6      * @authorXiehejun7      * 8      */9      Public classSynchronizedthread {Ten   One         classBank { A   -             Private intaccount = 100; -   the              Public intGetaccount () { -                 returnAccount ; -             } -   +             /** - * Implemented with synchronous method +              *  A              * @param Money at              */ -              Public synchronized voidSaveintMoney ) { -Account + =Money ; -             } -   -             /** in * Implemented with synchronous code blocks -              *  to              * @param Money +              */ -              Public voidSave1 (intMoney ) { the                 synchronized( This) { *Account + =Money ; $                 }Panax Notoginseng             } -         } the   +         classNewthreadImplementsRunnable { A             PrivateBank Bank; the   +              Publicnewthread (Bank bank) { -                  This. Bank =Bank; $             } $   - @Override -              Public voidrun () { the                  for(inti = 0; I < 10; i++) { -                     //bank.save1 (ten);WuyiBank.save (10); theSYSTEM.OUT.PRINTLN (i + "account balance:" +Bank.getaccount ()); -                 } Wu             } -   About         } $   -         /** - * Create threads, call internal classes -          */ A          Public voidUsethread () { +Bank Bank =NewBank (); theNewthread New_thread =Newnewthread (bank); -SYSTEM.OUT.PRINTLN ("Thread 1"); $Thread Thread1 =NewThread (new_thread); the Thread1.start (); theSYSTEM.OUT.PRINTLN ("Thread 2"); theThread thread2 =NewThread (new_thread); the Thread2.start (); -         } in   the          Public Static voidMain (string[] args) { theSynchronizedthread st =NewSynchronizedthread (); About St.usethread (); the         } the   the}
View Code3. Using special domain variables (volatile) to implement thread synchronization The A.volatile keyword provides a lock-free mechanism for accessing 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 operations, nor can it be used to modify the final type of the variable
 //just give the code that you want to modify, and the rest of the code        classBank {//variables that need to be synchronized plus volatile            Private volatile intaccount = 100;  Public intGetaccount () {returnAccount ; }            //We don't need synchronized here anymore .             Public voidSaveintMoney ) { Account+=Money ; }}
View CodeNote: The non-synchronous problem in multi-threading is mainly in the reading and writing of the domain, and if the domain itself avoids this problem, it is not necessary to modify the method of manipulating the domain. With the final domain, locked-protected and volatile domains can avoid unsynchronized problems. 4. Using a re-entry lock to implement thread synchronization the Reentrantlock class is a re-entrant, mutex, and lock interface that implements the same basic behavior and semantics as using the Synchronized method and fast, and expands its capabilities
classBank {Private intaccount = 100; //need to declare this lock            PrivateLock lock =NewReentrantlock ();  Public intGetaccount () {returnAccount ; }            //We don't need synchronized here anymore .             Public voidSaveintMoney )                {Lock.lock (); Try{ Account+=Money ; }finally{lock.unlock (); }}}
View CodeNote: The selection of the lock object and the Synchronized keyword: a. None of the best two, use a mechanism provided by a java.util.concurrent package that helps the user to handle all lock-related code.         B. If the synchronized keyword satisfies the user's needs, use synchronized because it simplifies the code C. If you need more advanced features, use the Reentrantlock class, you should pay attention to release the lock in time, otherwise there will be deadlock, 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, and the replicas are independent of each other so that each thread can modify its own copy of the variable without affecting other threads.
        Public classbank{//using the Threadlocal class to manage shared variable account            Private Staticthreadlocal<integer> account =NewThreadlocal<integer>() {@OverrideprotectedInteger InitialValue () {return100;            }            };  Public voidSaveintMoney ) {Account.set (Account.get ()+Money ); }             Public intGetaccount () {returnAccount.get (); }        }
View CodeNote: Threadlocal and synchronization mechanisms are both a.threadlocal and synchronous mechanisms to solve the problem of access violation of the same variable in multi-threading. B. The former adopts a "space-for-time" approach, which uses "time-for-space" approaches

Java Thread (1)-Thread synchronization

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.