并發(fā)編程總結(jié)

一.ReentrantLock總結(jié)

1.一些方法:
ReentrantLock reentrantLock = new ReentrantLock();
1)加鎖
reentrantLock.lock();
2)釋放鎖
reentrantLock.unlock();
3)嘗試獲取鎖 獲取不到返回false,獲取不到直接放棄,不進(jìn)入阻塞隊(duì)列
reentrantLock.tryLock();
4)在給定時(shí)間內(nèi)獲取鎖,獲取不到就退出
reentrantLock.tryLock(2, TimeUnit.SECONDS);
5)鎖綁定多個(gè)條件:一個(gè) ReentrantLock 可以同時(shí)綁定多個(gè) Condition 對(duì)象,更細(xì)粒度的喚醒線程,
通過(guò)reentrantLock.newCondition()創(chuàng)建一個(gè)條件變量condition
通過(guò)condition.await()方法,當(dāng)前線程進(jìn)入condition等待,釋放鎖;
通過(guò)condition.singal()方法,喚醒在condition中的線程;
6)reentrantLock.lockInterruptibly()`:獲得可打斷的鎖


public static void main(String[] args) throws InterruptedException {    
    ReentrantLock lock = new ReentrantLock();    
    Thread t1 = new Thread(() -> {        
        try {            
            System.out.println("嘗試獲取鎖");            
            lock.lockInterruptibly();        
        } catch (InterruptedException e) {            
            System.out.println("沒(méi)有獲取到鎖,被打斷,直接返回");            
            return;        
        }        
        try {            
            System.out.println("獲取到鎖");        
        } finally {            
            lock.unlock();        
        }    
    }, "t1");    
    lock.lock();    
    t1.start();    
    Thread.sleep(2000);    
    System.out.println("主線程進(jìn)行打斷鎖");    
    t1.interrupt();
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容