What are reentrant locks ?

It can prevent deadlock , It's the same lock

code :
package com.javaliao.backstage; class Phone{ public synchronized void
sendSMS(){ System.out.println(Thread.currentThread().getName()+"\t send message ");
sendEmail(); } public synchronized void sendEmail(){
System.out.println(Thread.currentThread().getName()+"\t send emails "); } } public class
Demo { public static void main(String[] args) { Phone phone = new Phone(); new
Thread(()->{ phone.sendSMS(); },"t1").start(); new Thread(()->{
phone.sendSMS(); },"t2").start(); } }
Console :

Life case :

There is a lock on the front door of the house , The toilet is not locked . I went through the gate , You don't have to lock the toilet .

ReentrantLock It's a reentrant lock
package com.javaliao.backstage; import java.util.concurrent.locks.Lock; import
java.util.concurrent.locks.ReentrantLock; class Phone implements Runnable{ Lock
lock = new ReentrantLock(); @Override public void run() { sendSMS(); } public
void sendSMS(){ // If you add a few, you have to unlock it several times lock.lock(); lock.lock(); try {
System.out.println(Thread.currentThread().getName()+"\t send message "); sendEmail(); }
finally { lock.unlock(); lock.unlock(); } } public void sendEmail(){
lock.lock(); try { System.out.println(Thread.currentThread().getName()+"\t
send emails "); } finally { lock.unlock(); } } } public class Demo { public static void
main(String[] args) { Phone phone = new Phone(); Thread t1 = new
Thread(phone,"t1"); Thread t2 = new Thread(phone,"t2"); t1.start(); t2.start();
} }







©2019-2020 Toolsou All rights reserved,
Python Garbage collection and memory leak hive Summary of processing methods for a large number of small files The difference between memory overflow and memory leak , Causes and Solutions Create data mysql Library process You don't know ——HarmonyOS stay Vue Use in Web WorkerSparkSQL Achieve partition overlay write msf Generate Trojan horse attack android mobile phone Linux Page replacement algorithm C Language implementation Django Personal blog building tutorial --- Time classified archiving