Multithreading--Concurrent access to objects and variables

Source: Internet
Author: User
Tags mutex volatile

1. Multiple threads accessing multiple objects The JVM creates multiple locks.
2. Static methods are synchronized in the same class-for all static methods in the same class, only one thread is allowed to execute one of the static methods at the same time, and the remaining threads that want to enter these methods must suspend waiting. Non-static methods are synchronized in the object unit.
3. Suppose that there are two threads A and B, one object, and thread A is acquiring a lock on the object that the M1 method is in when thread A calls a synchronous method of M1, so the other threads must wait for thread A to finish before calling method M1. If thread B calls the synchronous method of object M2, it must wait for thread A to finish executing the M1 method, that is, to release the object lock before it can be called, but thread B can call other non-synchronous methods at will.
4. The synchronized has the ability to lock re-entry (oneself can obtain its own internal lock again): When a thread acquires an object lock, it can again obtain the lock of the object once it is requested again. The other synchronization methods/blocks that call this class inside a synchronous method/block are always able to get locks. A reentrant lock also supports a relationship that inherits from a parent-child class in which a subclass can invoke a synchronous method of the parent class through a reentrant lock.

/*** This class is used to demonstrate the concept of lock re-entry * can be re-entered lock: You can get your own internal lock again. For example, when a thread acquires a lock on an object, the object is not released and is still available when it wants to acquire the lock again, * if it is not locked, it will cause a deadlock, and when there is a parent-child integration relationship, the subclass can call the parent class's synchronization method through a "reentrant lock" * @ Description *@authorNiepei * @date April 25, 2017 pm 3:52:41 *@versionV1.3.1*/ Public classLockreentry { Public synchronized voidService1 () {System.out.println ("Service1");  This. Service2 (); }     Public synchronized voidService2 () {System.out.println ("Service2");  This. Service3 (); }     Public synchronized voidService3 () {System.out.println ("Service3"); }     Public Static voidMain (string[] args) {thread thread=NewThread () {@Override Public voidrun () {Lockreentry service=NewLockreentry ();            Service.service1 ();        }        };    Thread.Start (); }}

5. when a thread executes a code exception, the lock it holds is automatically freed .
6. synchronization cannot be inherited , such as the service () method of the parent class is synchronous, the subclass inherits the parent class, and the Service () method in the subclass needs to be declared as synchronized.
7. When using the synchronized code block, it is important to note that if a thread accesses a synchronous block of code for object, access to all other synchronization blocks of the same object by other threads will be blocked
8. Multi-threaded deadlock: When the two sides hold each other's locks, there will be a deadlock, that is, as long as waiting for each other to release the lock can be a deadlock. The following code is a thread deadlock example:

 Public classDeadthreadImplementsRunnable {PrivateString username; PrivateObject Lock1 =NewObject (); PrivateObject Lock2 =NewObject ();  Public voidSetflag (String username) { This. Username =username; } @Override Public voidrun () {if(Username.equals ("a")) {            synchronized(lock1) {System.out.println ("Username =" +username); Try{Thread.Sleep (1000); } Catch(Exception e) {e.printstacktrace (); }                synchronized(Lock2) {System.out.println ("Executed by LOCK1, Lock2 code Order"); }            }        }        if(Username.equals ("B")) {            synchronized(Lock2) {System.out.println ("Username =" +username); Try{Thread.Sleep (1000); } Catch(Exception e) {e.printstacktrace (); }                synchronized(lock1) {System.out.println ("Executed by Lock2, Lock1 code Order"); }            }        }    }     Public Static voidMain (string[] args)throwsinterruptedexception {deadthread dt=NewDeadthread (); Dt.setflag (A); Thread a=NewThread (DT); A.setname (A);        A.start (); Thread.Sleep (1000); Dt.setflag ("B"); Thread b=NewThread (DT); B.setname (B);    B.start (); The result of the operation is: Username=Ausername= b

9. The volatile keyword is used to make instance variables visible across multiple threads, forcing the value of a variable to be taken from the public stack instead of getting the value of the variable from the thread's private data stack.

    • Volatile is a lightweight implementation of thread synchronization, so performance is certainly better than synchronized, and volatile can only be used to modify variables, while synchronized can modify methods, code blocks
    • Multi-threaded access volatile does not block, and synchronized can become blocked
    • Volatile can guarantee the visibility of data, but it does not guarantee atomicity, and synchronized can guarantee both atomicity and visibility (by synchronizing private memory and public memory data)
    • Volatile addresses the visibility of variables across multiple threads, while synchronized solves the synchronization of access resources between multiple threads
    • Thread safety includes atomicity and synchronization, and Java's synchronization mechanism is all about these two aspects to ensure thread-safe

The Synchronized keyword guarantees that only one thread can execute a method or a block of code at the same time, and that he contains two features: Mutex and visibility. synchronized not only resolves a thread to see that the object is in an inconsistent state, but also ensures that every thread that enters the synchronization method or synchronizes the code block sees all the results of the modification before being protected by the same lock

11. Class Reentrantlock has the effect of completely exclusive exclusivity, that is, only one thread at a time can execute code behind lock, which ensures that the instance variable is safe but less efficient, You can use the Reentrantreadwritelock class without solving this problem. In some methods that do not need to use instance variables, Reentrantreadwritelock can be used to improve efficiency. The read-write lock also has two locks, one read lock (shared lock) and one write lock (mutex). Read-only shared, read-write mutex, write mutex. That is, multiple threads can read at the same time, but only one thread can write at the same time.

 PackageCn.com.thread;ImportJava.util.concurrent.locks.ReentrantReadWriteLock; Public classReadwritelock {PrivateReentrantreadwritelock lock =NewReentrantreadwritelock ();  Public voidRead () {Try{lock.readlock (). Lock (); System.out.println (Thread.CurrentThread (). GetName ()+ "at" + system.currenttimemillis ()/1000 + "time to get a read lock"); Thread.Sleep (1000); } Catch(Exception e) {e.printstacktrace (); } finally{lock.readlock (). Unlock (); }    }     Public voidwrite () {Try{lock.writelock (). Lock (); System.out.println (Thread.CurrentThread (). GetName ()+ "at" + system.currenttimemillis ()/1000 + "time to get a write lock"); Thread.Sleep (1000); } Catch(Exception e) {e.printstacktrace (); } finally{lock.writelock (). Unlock (); }    }     Public Static voidMain (string[] args) {//Read ShareTestreadreadlock (); /*** The results are as follows: * R1 acquired a read lock at 1493257634 hours * R2 acquired a read lock in 1493257634 moments*/        //read-write MutexTestreadwritelock (); /*** The results are as follows: * R acquired a read lock at 1493258342 time * W acquired a write lock at 1493258343 time*/        //Write -write mutexTestwritewritelock (); /*** The results are as follows: * W1 acquired a write lock at 1493259822 hours * W2 got a write lock in 1493259823 moments*/    }     Public Static voidTestreadreadlock () {Readwritelock lock=NewReadwritelock (); NewReadthread ("R1", Lock). Start (); NewReadthread ("R2", Lock). Start (); }     Public Static voidTestreadwritelock () {Readwritelock lock=NewReadwritelock (); NewReadthread ("R", Lock). Start (); NewWritethread ("W", Lock). Start (); }     Public Static voidTestwritewritelock () {Readwritelock lock=NewReadwritelock (); NewWritethread ("W1", Lock). Start (); NewWritethread ("W2", Lock). Start (); }}/*** Read Thread * @Description *@authorNiepei * @date April 27, 2017 morning 10:05:57 *@versionV1.3.1*/classReadthreadextendsThread {PrivateReadwritelock Lock;  PublicReadthread (String name, Readwritelock Lock) {Super(name);  This. Lock =Block; } @Override Public voidrun () {lock.read (); }}/*** Write Thread * @Description *@authorNiepei * @date April 27, 2017 morning 10:05:46 *@versionV1.3.1*/classWritethreadextendsThread {PrivateReadwritelock Lock;  PublicWritethread (String name, Readwritelock Lock) {Super(name);  This. Lock =Block; } @Override Public voidrun () {lock.write (); }}

Multithreading--Concurrent access to objects and variables

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.