- ReentrantLock的可重入性
public class ReentrantLockTest01 {
public static void main(String[] args) {
//默认为非公平锁
ReentrantLock lock = new ReentrantLock();
//在同一线程中,ReentrantLock锁可重入(可重入:同一线程可以多次获取同一个锁)
for (int i = 0; i < 3; i++) {
System.out.println("lock");
lock.lock();
System.out.println("hold count is: " + lock.getHoldCount());
}
for (int j = 0; j < 3; j++) {
System.out.println("unlock");
//注意lock和unlock必须要成对出现,一般unlock会放在finally中
lock.unlock();
}
}
}
- 多线程场景
public class ReentrantLockTest02 {
//默认为非公平锁
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Thread(new MyThread()).start();
}
}
static class MyThread implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName() + " 加锁");
lock.lock();
try {
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + " 执行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + " 释放锁");
lock.unlock();
}
}
}
}
- ReentrantLock的可中断性
public class ReentrantLockTest03 {
//默认为非公平锁
private static ReentrantLock lock01 = new ReentrantLock(false);
private static ReentrantLock lock02 = new ReentrantLock(false);
public static void main(String[] args) {
//创建死锁场景
Thread thread01 = new Thread(new MyThread(lock01,lock02));
Thread thread02 = new Thread(new MyThread(lock02,lock01));
thread01.start();
thread02.start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
//中断其中一个线程
thread01.interrupt();
}
static class MyThread implements Runnable {
Lock firstLock;
Lock secondLock;
MyThread(Lock firstLock,Lock secondLock){
this.firstLock = firstLock;
this.secondLock = secondLock;
}
public void run() {
try {
//锁的可中断处理
firstLock.lockInterruptibly();
System.out.println(Thread.currentThread().getName()+" 获取锁:"+firstLock.toString());
TimeUnit.SECONDS.sleep(2);
secondLock.lockInterruptibly();
System.out.println(Thread.currentThread().getName()+" 获取锁:"+secondLock.toString());
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//注意释放锁
firstLock.unlock();
secondLock.unlock();
System.out.println(Thread.currentThread().getName()+" 处理完毕");
}
}
}
}
参考:
- https://www.cnblogs.com/gxyandwmm/p/9387833.html
- https://www.cnblogs.com/takumicx/p/9338983.html