The following is an example of waiting for each other to release the lock, the program will never stop
package pri.lsx.test.thread.reentrantlock; import java.util.concurrent.locks.ReentrantLock; /** * Use of reentrant lock * 1: Check if new ReentrantLock(); is an object lock or a class lock. Answer: A reentrant lock is an object lock *2: The way to construct a deadlock * * @author lisx * @date 2018-04-30 */ public class ReentrantLockUser { public static void main(String[] args) { // Start building a deadlock, waiting for each other to release the lock. Thread threadThree = new Thread(new DeadLockThrad(1), "thread3"); Thread threadFour = new Thread(new DeadLockThrad(99999999), "thread44444444444444444444444444444444444444444"); threadThree.start(); threadFour.start(); } } class DeadLockThrad implements Runnable { static ReentrantLock loclOne = new ReentrantLock(); // Note that this is static, indicating that the lock scope is the same as the class lock scope static ReentrantLock loclTwo = new ReentrantLock(); // Note that this is static, indicating that the lock scope is the same as the class lock scope int i; DeadLockThrad(int i) { this.i = i; } @Override public void run() { if (1 == i) { // get one lock first and then two locks loclOne.lock(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace (); } finally { loclTwo.lock(); loclOne.unlock(); loclTwo.unlock(); } } else { // first get two locks and then one lock loclTwo.lock(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace (); } finally { loclOne.lock(); loclTwo.unlock(); loclOne.unlock(); } } } }