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();
} }

 

 

 

 

 

 

Technology
©2019-2020 Toolsou All rights reserved,
Final review of database : Summary of comprehensive application questions Laplance operator ( Second derivative ) Simple learning of computer composition principle pyqt Button call python program _PyQt: Link button to function in program How much can you go up once you change jobs ? Today, I saw the ceiling of job hopping python in str Function usage _python in str Usage Summary of built-in functions MySQL trigger web The server nginx---linux Installation and deployment C++ Chapter V polymorphism exercises :( It's coming to an end )python Check built-in functions , How to check python Built in function