可重入锁 发表于 2020-11-18 | 分类于 并发编程 | 字数统计: 320 | 阅读时长 ≈ 1 什么是 “可重入”,可重入就是说某个线程已经获得某个锁,可以再次获取锁而不会出现死锁。例如 1234567891011121314151617181920212223242526package com.test.reen;// 演示可重入锁是什么意思,可重入,就是可以重复获取相同的锁,synchronized和ReentrantLock都是可重入的// 可重入降低了编程复杂性public class WhatReentrant { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { synchronized (this) { System.out.println("第1次获取锁,这个锁是:" + this); int index = 1; while (true) { synchronized (this) { System.out.println("第" + (++index) + "次获取锁,这个锁是:" + this); } if (index == 10) { break; } } } } }).start(); }} 123456789101112131415161718192021222324252627282930313233343536373839404142434445package com.test.reen;import java.util.Random;import java.util.concurrent.locks.ReentrantLock;// 演示可重入锁是什么意思public class WhatReentrant2 { public static void main(String[] args) { ReentrantLock lock = new ReentrantLock(); new Thread(new Runnable() { @Override public void run() { try { lock.lock(); System.out.println("第1次获取锁,这个锁是:" + lock); int index = 1; while (true) { try { lock.lock(); System.out.println("第" + (++index) + "次获取锁,这个锁是:" + lock); try { Thread.sleep(new Random().nextInt(200)); } catch (InterruptedException e) { e.printStackTrace(); } if (index == 10) { break; } } finally { lock.unlock(); } } } finally { lock.unlock(); } } }).start(); }}