A synchronized keyword
1.synchronized Implementation principle:---Object-based monitor (lock)
All objects in Java automatically contain a single lock, and the JVM is responsible for tracking how many times the object is locked. If an object is unlocked, its count becomes 0. The count becomes 1 when the task (thread) locks the object for the first time. Each time the same task (thread) obtains a lock on this object, the count is incremented. Only the task (thread) that acquires the lock first can continue to acquire multiple locks on the object. Each time the task leaves, the Count decrements, and when the count is 0, the lock is completely released.
Each object or class in Java has a lock associated with it, and for an object, the object is monitored for instance variables, and for classes, class variables are monitored (a class is itself a class object, so the lock associated with the class is also an object lock)
One thread executes the mutex code procedure as follows:
1. Obtain the synchronous lock;
2. Clear the working memory;
3. Copy the object from the main memory to the working memory;
4. Execute the code (calculation or output, etc.);
5. Refresh the main memory data;
6. Release the sync lock.
Therefore, synchronized not only guarantees the concurrent order of multithreading, but also ensures the memory visibility of multithreading.
2. How to use:
There are two ways to use the Synchronized keyword: thesynchronized method and the synchronized block . Both of these monitoring areas are associated with an incoming object, and when it reaches the monitoring area, the JVM locks the reference object and releases the lock on the referenced object when it leaves (the JVM releases the lock when an exception exits). Object locks are internal to the JVM, requiring only the synchronization method or synchronization block to be written, and the JVM automatically acquires or releases locks when the monitoring area is manipulated.
When synchronized acts on a method, the object instance (this) is locked and the class instance (class) corresponding to the object is locked when acting on a static method.
Two JavaSE5.0 added a java.util.concurrent package to support synchronization, Reentrantlock class.
1.Reentrantlock class
Common methods of the Reenreantlock class are:
Reentrantlock (): Create an Reentrantlock instance
Lock (): Get lock
Unlock (): Release lock
Note: 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
Two kinds of multithreading synchronization mechanism code implementation:
PackageCom.test1;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classThreadTest { Publicthreadtest () {Bank B=NewBank (); Thread T1=NewThread (b); Thread T2=NewThread (b); Thread T3=NewThread (b); T1.start (); T2.start (); T3.start (); } Public Static voidMain (string[] args) {threadtest threadtest=Newthreadtest (); } } classBankImplementsrunnable{Private intaccount=100; //thread synchronization mechanism 1: Thread synchronization method synchronized or synchronized{} modifies the execution statement block of a shared variable Public synchronized voidMinus_syn () { account--; System.out.println (Thread.CurrentThread (). GetName ()+ "account=" +Account ); } //thread synchronization mechanism 2: Thread synchronization with a re-entry lock /*** A java.util.concurrent package has been added in JavaSE5.0 to support synchronization. The Reentrantlock class is a re-entrant, mutex, implementation lock interface, which has the same basic behavior and semantics as using the Synchronized method and fast, and extends its ability to reenreantlock classes in a common way: Reentra NTLock (): Create a Reentrantlock Instance lock (): Get Lock Unlock (): Release lock Note: Reentrantlock () also has a construction method that can create a fair lock, but because it can significantly reduce Program run efficiency, not recommended*/ PrivateLock lock =NewReentrantlock (); Public voidMinus_lock () {lock.lock (); Try{ Account--; System.out.println (Thread.CurrentThread (). GetName ()+ "account=" +Account ); }finally{lock.unlock (); }} @Override Public voidrun () {//TODO auto-generated Method Stub while(true){ Try{Thread.Sleep (10); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } /*Synchronized Sync block * * Synchronized (this) {if ( account>0) {account-=1; System.out.println (Thread.CurrentThread (). GetName () + "account=" +account); } else break; }*/ /*Synchronized Method * * Minus_syn (); if (account<0) break;*/ //Reentrantlock class LockMinus_lock (); if(account<0) Break; } } }
Go Summary
1, the scope of the SYNCHRONIZED keyword has two kinds:
1) is within an object instance, synchronized Amethod () {} can prevent multiple threads from accessing the object's synchronized method at the same time (if an object has multiple synchronized methods, As long as a thread accesses one of the synchronized methods, the other thread cannot access any of the synchronized methods in the object at the same time. At this point, the synchronized method of the different object instances is not interfering. In other words, other threads can access the Synchronized method in another object instance of the same class at the same time;
2) is the scope of a class, synchronized static astaticmethod{} prevents multiple threads from accessing the synchronized static method in this class at the same time. It can work on all object instances of the class.
2, in addition to the method before using the Synchronized keyword, the synchronized keyword can also be used in a block in the method, indicating that only the resources of this block to implement mutually exclusive access. The usage is: synchronized (this) {/* block */}, which is scoped to the current object;
3, synchronized keyword is not inherited, that is, the method of the base class synchronized F () {} is not automatically synchronized F () {} in the inheriting class, but instead becomes F () {}. Inheriting a class requires that you explicitly specify one of its methods as the Synchronized method;
The Java language keyword that, when used to decorate a method or a block of code, guarantees that at most one thread executes the code at the same time.
First, when two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.
Second, however, when a thread accesses one synchronized (this) of an object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in the object.
Third, in particular, when a thread accesses one synchronized (this) of an object to synchronize a block of code, other threads will block access to all other synchronized (this) synchronization blocks in object.
See online some said volatile and threadlocal can also be used for thread synchronization, the statement is not accurate!
Talk about the Java keyword volatile and threadlocal classes later
Methods of multithreading synchronization in Java