Java Concurrency Program Design (12) Concurrent lock can be re-entered lock Reentrantlock

Source: Internet
Author: User

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

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.