Introduction to the usage of counterexamples and positive examples of Java ReentrantLock
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!