Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to replace synchronized with reentrantlock in java

Shulou Source: shulou.com Published: 2022-06-02 08:28:31 10月03日 Update

This article mainly explains "how to replace synchronized with reentrantlock in java". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to replace synchronized with reentrantlock in java".

Note: reentrantlock must release the lock manually.

Synchronized is locked manually and released automatically. Reentrantlock is automatically locked and released automatically.

Effect: m2 code can not be executed until M1 is executed:

/ * reentrantlock is used to replace synchronized * because M1 locks this, m2 can only be executed when M1 finishes execution * here is a review of the original semantics of synchronized * * the same function can be done with reentrantlock * it is important to note that the lock must be released manually (say the important thing three times) * if an exception is encountered with syn lock, jvm will automatically release the lock But lock must release the lock manually, so lock release is often done in finally * @ author mashibing * / package yxxy.c_020 Import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class ReentrantLock2 {Lock lock = new ReentrantLock (); void M1 () {/ / write try...catch..finally or try..finally try {lock.lock () / / synchronized (this) for (int I = 0; I < 10; iTunes +) {TimeUnit.SECONDS.sleep (1); System.out.println (I);}} catch (InterruptedException e) {e.printStackTrace () } finally {/ / release lock lock.unlock ();}} void m2 () {/ / lock the same lock to mutually exclusive lock.lock (); System.out.println ("m2...") Lock.unlock ();} public static void main (String [] args) {ReentrantLock2 rl = new ReentrantLock2 (); new Thread (rl::m1). Start (); try {TimeUnit.SECONDS.sleep (1) } catch (InterruptedException e) {e.printStackTrace ();} new Thread (rl::m2) .start () }} Thank you for your reading, the above is the content of "how to replace synchronized with reentrantlock in java". After the study of this article, I believe you have a deeper understanding of how to replace synchronized with reentrantlock in java, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Manual learning content original important things code functions only that is ideas situations effects articles times more knowledge knowledge points articles semantics Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Huawei OPPO Reno MySQL NVidia