ReentrantLock

ReentrantLock比Synchronized更加灵活。
ReentrantLock reentrantLock = new ReentrantLock();
ReentrantLock有以下几个重要的方法:
reentrantLock.lock(),//上锁
reentrantLock.unlock(); //释放锁
reentrantLock.isHeldByCurrentThread(); //判断当前线程是否上锁,一般在释放锁是判断,如果reentrantLock.lock()失败,finally块中reentrantLock.unlock()会报错,所以在reentrantLock.unlock()之前,先用 reentrantLock.isHeldByCurrentThread();判断

try {
            reentrantLock.lock();
        } finally {
        if(reentrantLock.isHeldByCurrentThread()){
            reentrantLock.unlock();
         }    
        }

reentrantLock.tryLock(); //尝试获取锁。重载类可以传入获取锁的时间,超时就不等待了。

让未获取到锁的线程中断用以下两个方法。

reentrantLock.lockInterruptibly();
thead.interrupt();

posted @ 2025-07-10 22:47  Charlie-Pang  阅读(8)  评论(0)    收藏  举报