ReentrantLock 可重入锁 ,实现了Lock 接口 ,是AQS框架的具体实现 。支持重入,等待超时,响应中断,公平和非公平锁。
ReentrantLock 使用
例1
public class ReentrantLockTest {
//两个线程同时去跑同一个方法 ,模拟竞争场景
public static void main(String[] args) {
ReentrantLockTest r = new ReentrantLockTest();
Lock lock = new ReentrantLock();
new Thread(()->{
r.test(lock);
}).start();
new Thread(()->{
r.test(lock);
}).start();
}
public void test (Lock lock){
try {
lock.lock();
System.out.println("线程"+Thread.currentThread().getName()+"获取到锁");
Thread.sleep(2000);
}catch (Exception e){
}finally {
lock.unlock();
System.out.println("线程"+Thread.currentThread().getName()+"释放锁");
}
}
}
控制台打印
线程Thread-0获取到锁
线程Thread-0释放锁
线程Thread-1获取到锁
线程Thread-1释放锁
为了避免死锁,一般将释放锁动作放在finally块中 ,当try 块中发生异常时也能最终释放锁
例2
public class ReentrantLockTest2 {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Mythread threada = new Mythread(lock);
Mythread threadb = new Mythread(lock);
threada.start();
threadb.start();
}
public static void test(Lock lock) throws InterruptedException {
if (lock.tryLock(2000, TimeUnit.MILLISECONDS)) {
try {
System.out.println("线程" + Thread.currentThread().getName() + "获取到锁");
Thread.sleep(4000);
} finally {
lock.unlock();
System.out.println("线程" + Thread.currentThread().getName() + "释放掉了锁");
}
} else {
System.out.println("线程" + Thread.currentThread().getName() + "放弃了获取锁");
}
}
}
class Mythread extends Thread {
private Lock lock;
public Mythread(Lock lock) {