1. Why does the lock appear?
Before JDK5, we usually use synchronized to do the lock operation, but synchronized is a pessimistic lock, if the thread that acquires the lock is blocked, but does not release the lock, the other threads will only wait indefinitely. Lock enables other threads to wait only for a certain amount of time or to respond to interrupts.
Another example is that when there are multiple threads reading and writing to a file, there is a conflict between the read and write operations, and the write and write operations conflict, but there is no conflict between read and read operations.
If you use the Synchronized keyword for synchronization, it can cause a problem: If multiple threads are simply reading, the other thread can only wait for the read operation when a thread is reading. Therefore, a mechanism is needed to enable multiple threads to simply read, and there will be no conflicts between threads, which can be done by lock.
And through lock can know the line threads did not successfully acquire the lock, and this synchronized is impossible to do.
2. Lock is different from synchronized's place?
1. Lock lock is manually implemented by code, after locking, we need to manually release the lock, do not release the word will most likely deadlock problem, and synchronized is the Java keyword, is implemented by the JVM, Synchronized the JVM automatically releases the lock when the method throws an exception when the code block performs a play or lock;
2. Lock can be used to know if there is a successful acquisition of locks, and synchronized is unable to do;
3. Lock allows the thread waiting for the lock to respond to interrupts, while synchronized does not, while using synchronized, the waiting thread waits until it is not able to respond to interrupts
3. Lock interface Method Introduction
Packagejava.util.concurrent.locks;ImportJava.util.concurrent.TimeUnit;/** * @since 1.5 * @author Doug Lea*/ Public InterfaceLock {/*** Gets the lock operation, if the lock is occupied by another thread, waits, the interface uses up to*/ voidLock (); /*** Interrupt the wait process, if thread A gets the lock, and thread B is waiting, then call the method to be able to break thread B in the waiting process. And if a thread has acquired a lock, it will not be interrupted by the method. Be aware that the method throws an exception*/ voidLockinterruptibly ()throwsinterruptedexception; /*** Trylock is used to attempt to acquire a lock, and if it succeeds, returns true if the fetch fails (the lock is fetched by another thread) and returns false, saying that the method returns immediately anyway. You won't be waiting there until you get the lock. * Lock lock = ...; * IF (Lock.trylock ()) {* try {* ... *} finally {* Lock.unlock (); *} *} else {* ... *} **/ BooleanTrylock (); /*** Similar to the Trylock method, but the method will wait for a certain time when the lock is not taken, if it is not in the time period of the lock, it returns FALSE, if the lock is received within this time, then returns true;*/ BooleanTrylock (LongTime, Timeunit unit)throwsinterruptedexception; /*** Method of releasing locks, generally used for release in finally*/ voidunlock (); /***/Condition newcondition ();}
Attention:
Because lock is to be released manually, the general use of lock must be done in try{}catch{}, where the lock is released in finally;
Lock lock = ...; Lock.lock (); Try { / / Processing Task catchfinally { // release Lock }
4. Generally we can operate through Reentrantlock, Reentrantlock is the implementation class of lock;
A. testlockinterruptibly
/*** testlockinterruptibly * *@paramThread the thread*/ Private voidtestlockinterruptibly (thread thread)throwsinterruptedexception{if(Lock.trylock ()) {Try{System.out.println ("Current Thread" + thread.getname () + "Got the lock!"); Thread.Sleep (3000); } Catch(Exception e) {e.printstacktrace (); } finally{System.out.println ("Current Thread" + thread.getname () + "Release the lock!"); Lock.unlock (); } } Else{System.out.println ("Thread" + thread.getname () + "interrupted!" "); Lock.lockinterruptibly (); } } Public Static voidMain (string[] args) {main main=NewMain (); NewThread (() { Try{main.testlockinterruptibly (Thread.CurrentThread ()); } Catch(interruptedexception e) {e.printstacktrace (); }}). Start (); NewThread (() { Try{main.testlockinterruptibly (Thread.CurrentThread ()); } Catch(interruptedexception e) {e.printstacktrace (); }}). Start (); }
The current thread Thread-0 got the lock! Threading Thread-1 interrupted! Thread 0 of current threadsreleased the lock!
B. Testlock,testtrylock:
/*** Test lock. * * @paramThread the thread*/ Private voidtestlock (thread thread) {lock.lock (); Try{System.out.println ("Current Thread" + thread.getname () + "Get the lock!" "); } Catch(Exception e) {}finally{System.out.println ("Current Thread" + thread.getname () + "Release the lock!" "); Lock.unlock (); } } /*** Test Trylock. * * @paramThread the thread*/ Private voidtesttrylock (thread thread) {if(Lock.trylock ()) {Try{System.out.println ("Current Thread" + thread.getname () + "Got the lock!"); } Catch(Exception e) {e.printstacktrace (); } finally{System.out.println ("Current Thread" + thread.getname () + "Release the lock!"); Lock.unlock (); } } Else{System.out.println ("Someone takes a lock, thread" + thread.getname () + "Can't get the lock"); } } Public Static voidMain (string[] args) {main main=NewMain (); NewThread (()Main.testlock (Thread.CurrentThread ())). Start (); NewThread (()Main.testlock (Thread.CurrentThread ())). Start (); }
Another lock is a read-write lock: Readwritelock, which has only two methods, one for the read lock and one for the write lock. This means separating the read and write operations of the file into 2 locks to be allocated to the thread, allowing multiple threads to read concurrently.
The Reentrantreadwritelock implements the Readwritelock interface.
So, in terms of performance, if the competitive resources are not fierce, the performance of the two is similar, and when the competitive resources are very intense (that is, there are a lot of threads competing at the same time), at this time lock performance is far better than synchronized. Therefore, in the specific use, according to the appropriate circumstances to choose.
This article is referenced from: https://www.cnblogs.com/baizhanshi/p/6419268.html
Java-lock Introduction