Get the App
SLTechnology News&Howtos  ›  Development  › 

Introduction to the usage of counterexamples and positive examples of Java ReentrantLock

Shulou Source: shulou.com Published: 2022-06-03 17:27:51 09月11日 Update

This article mainly explains "Introduction to the use of counterexample and positive example of Java ReentrantLock". The explanation content in this article is simple and clear, easy to learn and understand. Please follow the idea of Xiaobian to study and learn "Introduction to the use of counterexample and positive example of Java ReentrantLock" together.

Release lock in finally

When using ReentrantLock, you must remember to release the lock, otherwise it will cause the lock to be occupied all the time, and other threads that use the lock will wait forever, so when we use ReentrantLock, we must release the lock in finally, so that we can ensure that the lock will be released.

counterexample

import java.util.concurrent.locks.ReentrantLock; publicclass LockExample { //Create lock object privatestaticfinal ReentrantLock lock = new ReentrantLock(); public static void main(String[] args) { //lock operation lock.lock(); System.out.println("Hello,ReentrantLock. "); //exception will be reported here, causing the lock not to be released properly int number = 1 / 0; //release lock lock.unlock(); System.out.println("Lock released successfully! "); }}

When an exception occurs and the lock is not released properly, other threads that use the lock are left in a permanent wait state.

positive examples

import java.util.concurrent.locks.ReentrantLock; publicclass LockExample { //Create lock object privatestaticfinal ReentrantLock lock = new ReentrantLock(); public static void main(String[] args) { //lock operation lock.lock(); try { System.out.println("Hello,ReentrantLock. "); //exception will be reported here int number = 1 / 0; } finally { //release lock lock.unlock(); System.out.println("Lock released successfully! "); } }}

Although an exception occurs in the method, it does not affect the release of the ReentrantLock lock, so that other threads using this lock can acquire and run normally.

Thank you for reading, the above is the "Java ReentrantLock counterexample and positive example usage introduction" content, after the study of this article, I believe that everyone on Java ReentrantLock counterexample and positive example usage introduction This problem has a deeper understanding, the specific use of the situation also needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Tags: Thread learning success content object situation will report permanent that is ideas articles methods more status knowledge knowledge points articles follow questions guarantee Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker OPPO Reno MySQL Shulou Tech Info MariaDB