Implementing thread Synchronization in Java

Source: Internet
Author: User
Tags volatile

Why use Sync? 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. 1. The synchronization method is a method of synchronized keyword modification. 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. Code such as: Public synchronized void Save () {} Note: The Synchronized keyword can also be used to decorate a static method, at which point the static method is called, and the entire class 2 is locked. The synchronization code block is a block of statements that have synchronized keyword adornments. The block of statements modified by this keyword is automatically added with the built-in lock, which enables synchronization of code such as: 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. code example: Copy code package com.xhj.thread; /** * Application of thread synchronization * * @author Xiehejun * */public class Synchronizedthread {class Bank {private Int. account = +; public I NT Getaccount () {return account;}/** * Implemented using synchronous method * * @param money */public synchronized void Save (Int. money) {account + = Money; }/** * Implemented with synchronous code block * * @param money */public void save1 (int. money) {synchronized (this) {account + + Money;}} Class Newthread implements Runnable {Private Bank Bank, Public Newthread (Bank) {this.bank = Bank;} @Override Publi C VoiD run () {for (int i = 0; i < i++) {//bank.save1 (+); Bank.save (10); SYSTEM.OUT.PRINTLN (i + "account balance:" + bank.getaccount ()); }}}/** * Create thread, call inner class */public void Usethread () {Bank Bank = new Bank (); Newthread new_thread = new Newthread (bank); SYSTEM.OUT.PRINTLN ("Thread 1"); Thread thread1 = new Thread (new_thread); Thread1.start (); SYSTEM.OUT.PRINTLN ("Thread 2"); Thread thread2 = new Thread (new_thread); Thread2.start (); } public static void Main (string[] args) {Synchronizedthread st = new Synchronizedthread (); St.usethread ();}} Copy Code 3. Use 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 use of the domain is recalculated, instead of using the value in the Register D.volatile does not provide any atomic operations, nor can it be used to decorate a variable of the final type, for example: In the example above, just precede the account with the volatile modifier, Thread synchronization can be implemented. code example: Copy code//give only the code to be modified, the rest of the code with the same class Bank {//The variables that need to be synchronized plus the volatile private volatile int account = +; public int Getaccount ( {return account;}//This is no longer required synchronized public void Save (int money) {account + + Money;}} Copy Code Note: The non-synchronization problem in multi-threading is mainly on the read and write of the domain , if you make the domain self-To avoid this problem, you do not need to modify the method that operates the field. With the final domain, locked-protected and volatile domains can avoid unsynchronized problems. 4. Using a re-entry lock to implement thread synchronization a new Java.util.concurrent package is added to support synchronization in JavaSE5.0. The Reentrantlock class is a re-entrant, mutex, implementation lock interface, which has the common method of using the Synchronized method with the same basic behavior and semantics as fast, and extends its ability to Reenreantlock classes: Reentrantlock ( ): Create a Reentrantlock Instance lock (): Get Lock Unlock (): Release lock Note: Reentrantlock () There is also a construction method that can create a fair lock, but it is not recommended to use for example: on the basis of the above example, because it can greatly reduce the efficiency of the program. , the rewritten code is: code example: Copy code//give only the code to be modified, the rest of the code with the same class Bank {private int account = 100;//need to declare this lock private lock lock = new Reentran Tlock (); public int Getaccount () {return account;}//The synchronized public void Save (int money) {Lock.lock () is no longer required here; try{Account + = Money; }finally{Lock.unlock ();}} Copy the code Note: The selection of the lock object and the Synchronized keyword: a. Preferably none of the 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 a deadlock, usually in the finally code release lock 5. Using local variables to implement thread synchronization if you use threadlocal to manage variables, Each thread that uses the variable obtains 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. Common methods of the ThreadLocal class ThreadLocal (): Create aThread local variable get (): Returns the value in the current thread copy of this thread's local variable InitialValue (): Returns the "initial value" set (T value) of the current thread of this thread's local variable: sets the value in the current thread copy of this thread's local variable to value for example: above On the basis of the example, the modified code is: code example: Copy code//Change Bank class, rest code with public class bank{//Use ThreadLocal class to manage shared variables account private static ThreadLocal account = new ThreadLocal () {@Override protected integer initialvalue () {return,}}; public void Save (int money) {Account.set (Account.get () +money),} public int getaccount () {return account.get ();}} Copy Code Note: The Threadlocal and synchronization mechanisms are both a.threadlocal and synchronous mechanisms to resolve access violation issues for the same variables in multiple threads. B. The former uses a "space-for-time" approach, which uses "time-to-space" in

Java for 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.