1.1. can be re-entered lock Reentrantlock
Reentrantlock is a reentrant lock available in the Java Concurrency Library. There are similarities and differences compared to synchronized synchronous blocks. Similar places are:
(1) can achieve synchronization between multiple threads, and avoid access violation of shared resources.
(2) Are reentrant, that is, a thread that has acquired a lock can get the same lock again, synchronized also similar.
The different places are:
(1) The Reentrantlock is more flexible, and acquiring and releasing locks can be in the same method or in different methods. synchronized are usually used in the same method body.
(2) the efficiency of Reentrantlock is higher than that of synchronized .
the problem to be aware of when using Reentrantlock is that the code protected by the lock should be placed in the try{} code block, andtheunlock operation is placed in the finally{} code block, avoid locks that are not released because of an exception before unlock after the lock operation .
//This is a shared resource class. classSharedResource {PrivateReentrantlock lock =NewReentrantlock (); Public voidVisitresource () {lock.lock ();Try{System.out.println ("Visitresource called:" +Thread.CurrentThread (). GetName ());}finally{Lock.unlock ();}}} Public classReentrantlocktest { Public Static voidMain (string[] args) {//Create a thread pool to submit 10 tasks. FinalSharedResource sr =NewSharedResource (); Executorservice Executorservice= Executors.newfixedthreadpool (3); for(inti=0;i<10;i++) {Executorservice.execute (NewRunnable () {@Override Public voidrun () {sr.visitresource ();//access shared resources. }});} Executorservice.shutdown ();}}
Java Concurrency Program Design (12) Concurrent lock can be re-entered lock Reentrantlock