Why use synchronization ?

    java Allow multithreading concurrency control , When multiple threads operate on a shareable resource variable at the same time ( Such as data addition, deletion, modification and query ), 
    It will lead to inaccurate data , Conflict with each other , So add a synchronization lock to avoid that before the thread does not complete the operation , Called by other threads , 
    Thus, the uniqueness and accuracy of the variable are guaranteed .
 
 

1. Synchronization method

    That is to say synchronized Methods of keyword modification . 
    because java Each object of has a built-in lock , When you decorate a method with this keyword , 
    The built-in lock will protect the whole method . Before calling this method , Need to get built-in lock , Otherwise, it will be blocked .
    Code such as : 
    public synchronized void save(){}
    notes : synchronized Keywords can also modify static methods , At this time, if the static method is called , Will lock the whole class
 
 

2. Synchronization code block

    That is to say synchronized Keyword decorated statement block . 
    The statement block decorated by the keyword will be automatically locked , To achieve synchronization
    Code such as : 
    synchronized(object){ 
    }
    notes : Synchronization is a high overhead operation , So try to minimize the content of synchronization . 
    There is usually no need to synchronize the entire method , Use synchronized Code block synchronization key code can .     
    Code instance : 
    
 
Copy code
package com.xhj.thread;
 
    /**
     * Use of thread synchronization
     * 
     * @author XIEHEJUN
     * 
     */
    public class SynchronizedThread {
 
        class Bank {
 
            private int account = 100;
 
            public int getAccount() {
                return account;
            }
 
            /**
             * Use synchronous method to realize
             * 
             * @param money
             */
            public synchronized void save(int money) {
                account += money;
            }
 
            /**
             * Using synchronous code block to realize
             * 
             * @param money
             */
            public void save1(int money) {
                synchronized (this) {
                    account += money;
                }
            }
        }
 
        class NewThread implements Runnable {
            private Bank bank;
 
            public NewThread(Bank bank) {
                this.bank = bank;
            }
 
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    // bank.save1(10);
                    bank.save(10);
                    System.out.println(i + " The account balance is :" + bank.getAccount());
                }
            }
 
        }
 
        /**
         * Set up threads , Calling inner class
         */
        public void useThread() {
            Bank bank = new Bank();
            NewThread new_thread = new NewThread(bank);
            System.out.println(" Threads 1");
            Thread thread1 = new Thread(new_thread);
            thread1.start();
            System.out.println(" Threads 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) Thread synchronization

 
    a.volatile Keyword provides a lock free mechanism for accessing domain variables , 
    b. Use volatile The modifier field is equivalent to telling virtual machine The domain may be updated by other threads , 
    c. So every time you use this domain, you have to recalculate , Instead of using the value in the register  
    d.volatile No atomic operation will be provided , It can't be used to decorate final Variable of type  
    
    for example : 
        In the example above , Just in account prefix volatile modification , To achieve thread synchronization . 
    
    Code instance : 
    
 
Copy code
      // Only give the code to be modified , The rest of the code is the same as above
        class Bank {
            // Variables that need to be synchronized plus volatile
            private volatile int account = 100;
 
            public int getAccount() {
                return account;
            }
            // There is no need for synchronized 
            public void save(int money) {
                account += money;
            }
        }
Copy code
 
    notes : The asynchronous problem in multithreading mainly occurs in reading and writing domain , If you let the domain itself avoid this problem , Then you don't need to modify the method to operate the domain . 
    use final Domain , Domain with lock protection and volatile Domain can avoid asynchronous problems . 
    

4. Use reentry lock to realize thread synchronization

 
    stay JavaSE5.0 There's a new java.util.concurrent Package to support synchronization . 
    ReentrantLock Class is reentrant 、 Mutually exclusive 、 Realized Lock Lock of interface , 
    It's used with synchronized Method and fast have the same basic behavior and semantics , And expanded its capabilities
 
 
    ReenreantLock The common methods of class are :
 
        ReentrantLock() : Create a ReentrantLock example  
        lock() : Gets the lock  
        unlock() : Release the lock  
    notes :ReentrantLock() There is also a construction method that can create fair locks , But because it can greatly reduce the efficiency of program operation , It is not recommended to use  
        
    for example : 
        On the basis of the above example , The rewritten code is : 
        
    Code instance : 
    
 
Copy code
// Only give the code to be modified , The rest of the code is the same as above
        class Bank {
            
            private int account = 100;
            // This lock needs to be declared
            private Lock lock = new ReentrantLock();
            public int getAccount() {
                return account;
            }
            // There is no need for synchronized 
            public void save(int money) {
                lock.lock();
                try{
                    account += money;
                }finally{
                    lock.unlock();
                }
                
            }
        }
Copy code
          
    notes : About Lock Objects and synchronized The choice of keywords : 
        a. It's better not to use either , Use a java.util.concurrent The mechanism provided by the package , 
            It can help the user to deal with all the lock related code . 
        b. If synchronized Keywords can meet the needs of users , Just use synchronized, Because it simplifies the code  
        c. If you need more advanced features , Just use ReentrantLock class , Pay attention to release the lock in time , Otherwise there will be deadlock , Usually in finally Code release lock  
        

5. Thread synchronization using local variables

    If you use ThreadLocal Manage variables , Then each thread using the variable gets a copy of the variable , 
    The copies are independent of each other , In this way, each thread can modify its own variable copy at will , It doesn't affect other threads .
 
 
 
    ThreadLocal Common methods of class
 
 
 
    ThreadLocal() : Create a thread local variable  
    get() : Returns the value in the current thread copy of this thread local variable  
    initialValue() : Returns the... Of the current thread for this thread's local variable " Initial value " 
    set(T value) : Set the value in the current thread copy of this thread local variable to value
 
 
 
    for example : 
        Based on the above example , The revised code is : 
        
    Code instance : 
        
 
Copy code
// Only change Bank class , The rest of the code is the same as above
        public class Bank{
            // Use ThreadLocal Class to manage shared variables account
            private static ThreadLocal<Integer> account = new ThreadLocal<Integer>(){
                @Override
                protected Integer initialValue(){
                    return 100;
                }
            };
            public void save(int money){
                account.set(account.get()+money);
            }
            public int getAccount(){
                return account.get();
            }
        }
Copy code
    notes :ThreadLocal And synchronization mechanism  
        a.ThreadLocal And synchronization mechanism are to solve the problem of access conflict of the same variable in multithreading . 
        b. The former uses " Space for time " Methods , The latter uses " Time for space " The way  

java note -- About thread synchronization (5 There are two ways to synchronize )【 turn 】 More articles about

  1. [ Reprint ]Java There are two ways to implement threads

    Reprint :http://baijiahao.baidu.com/s?id=1602265641578157555&wfr=spider&for=pc Preface A thread is an execution thread of a program , Executive Road ...

  2. Summary of concurrent programming series ( Thread safety ,synchronized, Dirty reading , Communication between threads wait/notify, There are three ways to implement threads Demo, Substitutable wait/notify Methods )

    Thread safety : When multiple threads access a class ( Object or method ) when , This class always behaves correctly , So this class ( Objects or methods are thread safe ) synchronized: You can lock any object or method , And the code that locks is called ...

  3. Java Use SFTP and FTP Two kinds of connection methods realize the upload and download of the server 【 I changed 】

    [] How to distinguish is the need to use SFTP still FTP? [] I think : 1. See if the private key is known . SFTP and FTP The main difference is SFTP There's a private key , That is, when you create a connection object ,SFTP In addition to the user name and password, you need to know ...

  4. Java Connect Oracle There are three ways to connect databases

    background : I'm studying these two days Oracle database , Here is a summary of what I have learned in class , At the same time, record , It's convenient to sort out the knowledge learned that day , At the same time, it is convenient for you to inquire in the future . SQL In words , I won't talk much about it here , Feel and other databases (MySQ ...

  5. Linux Several ways to end a thread

    Linux Create thread usage int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) ...

  6. java note -- About thread synchronization (7 There are two ways to synchronize )

    About thread synchronization (7 Ways of planting ) -- If you want to reprint this article, please indicate the reprint address "http://www.cnblogs.com/XHJT/p/3897440.html" thank you -- Why use synchronization ? ...

  7. Java Reading notes : Thread safety and mutex synchronization

    Catalog Causes of thread insecurity What is thread safety immutable Absolute thread safety Relative thread safety Thread compatibility Thread opposition Mutex synchronization for thread safety synchronized Built in lock A lock is an object Do you want to release the lock Realization principle What is reentry ? ...

  8. C# Reading notes : Threads , Tasks and synchronization

    Preface Study C# More than two months , Like when I was practicing PHP Development is the same , Also by one by one Feature demand , Slowly mastered a lot of related programming skills . This time mainly records the study C# Multithreading related knowledge . Reference books :<Csharp Advanced programming ...

  9. java note (5) —— Threads ,yield,join

    One . Thread states and transitions : New state : use new Statement creates a thread object in a new state , At this point it and others java object , Only memory is allocated in the heap . Ready state : When a thread is created , Other threads called its start() ...

  10. Java There are three ways to terminate a thread in

    The recommended way to terminate a thread is to let the thread end itself , Get into Dead( Death ) state , It's the end of execution run() Method . That is, if you want to stop the execution of a thread , We need to provide a way for threads to end automatically run() Method execution . Like setting up a sign to ...

Random recommendation

  1. ABP Audit log of theory learning

    Return to the general catalog This directory Introduce To configure Turn it on through features / close Be careful I'll give you an example of this project Introduce Wikipedia says : " Audit trail ( It's also called audit log ) It's a chronological record of safety , Record set or record source , They provide a sequence of activities ...

  2. NIS The client restricts users from logging in

    All account information of the company is provided by one NIS Server Unified management , But there are a few NIS Client Only a few users are allowed to log in . Through here PAM Mechanism to achieve this requirement . 1. Files that need to be configured (/etc/pam.d/ Under the table of contents ) ...

  3. Java GC Expert series 1: understand Java Garbage collection

    understand Java The garbage collection of (GC) What benefits can principles bring us ? For software engineers , Satisfying technical curiosity can be regarded as a , But it's important to understand GC Can help us better write Java Applications . The above is my personal subjective view , But I believe in ...

  4. [INS-40724] No locally defined network interface matches the SCAN subnet.

    The environment is as follows OS:AIX 7.1 DB:11.2.0.4 2 node RAC Error message In the installation 11.2.0.4 RAC The following error is reported INS-40724] No locally defined networ ...

  5. MySQL SQL Statement execution order

    MySQL The statements are divided into 11 Step , As shown in the figure below , The first thing to do is always FROM operation , The last thing to do is LIMIT operation . Each of these operations produces a virtual table , This virtual table serves as a processing input , It's just that these virtual tables are useful to users ...

  6. tablespace( Table space ) / segment( break ) / extent( Panel )/ block( block )/datafile( file ) The relationship between

    tablespace( Table space ) / segment( break ) / extent( Panel )/ block( block ) The relationship between   tablespace : A database is divided into one or more table logical units , The table space , Each table is empty ...

  7. iOS There are three ways to make a call

    , This method , You can't get back to the original app after dialing , Will stay in the address book , And it's a direct call , No pop-up prompts NSMutableString * str=[[NSMutableString alloc] initWithFo ...

  8. Android application development - Network programming ( One )

    Web image viewer 1. Determine the URL of the image 2. send out http request URL url = new URL(address); // Get the connection object between client and server , The connection has not been established yet HttpURLConnec ...

  9. servlet Why does it show up ?servlet What's the role ?

    I met this question in the interview , So I want to summarize , So I went online and looked for it , It's mainly some reasonable explanations on the Internet : servlet Why does it show up ? Servlet = Service + Applet, Represents a small service program .S ...

  10. C Dynamic linked list establishment of

    The function applied is : Dynamic memory allocation function malloc()               such as :char *name=(char *)malloc(20);   Equivalent to c++ Of new keyword Dynamic memory release function free ...