Several key concepts of threads----inter-thread communication; thread deadlock; line-programmed: Suspend, stop, and resume (5 ways to Thread sync)

Source: Internet
Author: User
Tags volatile

(i) thread synchronization (5 synchronization modes)

1. synchronization method ---> has synchronized keyword modification method . (each built-in object in Java has a built-in lock that protects the entire method---> built-in lock with the synchronized retouching method )

You need to get the built-in lock before calling the method , otherwise it will be in a blocking state .

Eg:public synchronized void Save () {}

Note : The synchronized keyword can also modify a static method, at which point the entire class is locked if the static method is called. "

2. synchronizing code blocks :---> statement blocks with synchronized keyword adornments. ( statement block is added with built-in lock )

Eg:synchronized (object) {} " synchronization is a high-overhead Operation---> Minimizes synchronization of content --often There is no need to synchronize the entire method and synchronize the key code .

Package com.xhj.thread;

    /**     * thread sync application      *      * @author Xiehejun&nbs P    *      */    public class Synchronizedthread {       &NBSP ; Class Bank {             private int account = 100;         &N Bsp   public int getaccount () {                return account;    &NBSP ;      }            /**             * Using synchronous method              *              * @param mo ney             */            public synchronized void SA ve (int money) {                account + + money;           }&NBSP;           /**             * Synchronize code block implementation     &NBS P        *              * @param money      &NBSP ;      */            public void save1 (int. money) {                synchronized (this) {                    ACC Ount + = money;               }           }  & nbsp    }         class Newthread implements Runnable {          & nbsp Private Bank bank;             public newthread (bank) {                This.bank = bank;           }             @Override             public void run () {            &N Bsp   for (int i = 0; i < i++) {                   //Bank.save 1;                    Bank.save (Ten);        &NBS P           SYSTEM.OUT.PRINTLN (i + "account balance:" + bank.getaccount ());               }           }        }     & nbsp  /**         * build thread, call internal class          */        PU Blic void Usethread () {            BANK bank = new Bank ();            Newthread new_thread = new Newthread (bank);            SYSTEM.OUT.PRINTLN ("Thread 1"); &NB Sp           Thread thread1 = new Thread (new_thread);            Thread1.sta RT ();            SYSTEM.OUT.PRINTLN ("Thread 2");            Thread Thread2 = new Thread (new_thread);            Thread2.start ();       }&N bsp;        public static void main (string[] args) {            Synchron Izedthread st = new Synchronizedthread ();            St.usethread ();      &NB Sp }    } ③: Implementing thread synchronization with special domain variables (volatile)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 RegisterD.volatile does not provide any atomic manipulation, nor can it be used to modify a final type of variableeg:

Note: 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. ④: using a re-entry lock for thread synchronization a java.util.concurrent package has been added to support synchronization in JavaSE5.0. The Reentrantlock class is a lock that can be re-entrant, mutually exclusive, and implements the lock interface.it has the same basic behavior and semantics as using the Synchronized method and fast, and expands its capabilities common methods of the Reenreantlock class are: Reentrantlock (): Create an Reentrantlock instanceLock (): Get lockunlock (): Release lockNote: Reentrantlock () also has a construction method that can create a fair lock, but is not recommended because it can significantly reduce the efficiency of program Operation        For example:On the basis of the above example, the rewritten code is:        code Example:     Copy Code//Give only the code you want to modify, and the rest of the codeclass Bank {            private int account = +;//need to declare this lockPrivate Lock lock = new Reentrantlock ();public int Getaccount () {return account;            }//No need for synchronized herePublic void Save (int money) {Lock.lock ();try{Account + = money;}finally{Lock.unlock ();                }                            }}Copy Code          Note: About the lock object and synchronized keyword selection:A. It is best to use one of the mechanisms provided by the java.util.concurrent package, preferably two.ability to help users with all lock-related code. B. If the synchronized keyword satisfies the user's needs, use synchronized because it simplifies the codec. 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⑤. Using local variables for thread synchronization If you use threadlocal to manage variables, each thread that uses the variable obtains a copy of the variable.replicas are independent of each other so that each thread is free to modify its own copy of the variable without affecting other threads.  
 Common methods of ThreadLocal class   ThreadLocal (): Create a thread-local variableget (): Returns the value in the current thread copy of this thread's local variableinitialvalue (): Returns the "initial value" of the current thread for this thread's local variablesSet (T value): Sets the value in the current thread copy of this thread's local variable to value   For example:on the basis of the above example, the modified code is:        code Example:         Copy Code//Change Bank class only, the rest of the codePublic class bank{//Use the Threadlocal class to manage shared variable accountprivate static threadlocal<integer> account = new threadlocal<integer> () {@Overrideprotected Integer InitialValue () {return;                }            };Public void Save (int money) {Account.set (Account.get () +money);            }public int Getaccount () {return Account.get ();            }        }Copy CodeNote: threadlocal and synchronization mechanismThe a.threadlocal and synchronization mechanisms are all designed 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

Several key concepts of threads----inter-thread communication; thread deadlock; line-programmed: Suspend, stop, and resume (5 ways to Thread sync)

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.