重入鎖的好搭檔:Condition條件
- Condition 條件與Object 的wait 和Object.notify 方法類似。
- Condition 有如下基本方法:
- await() 方法會(huì)使當(dāng)前獻(xiàn)策好難過等待,同時(shí)釋放當(dāng)前鎖,當(dāng)其他線程中使用signal() 或者使用signalAll()方法時(shí),線程會(huì)重新獲得鎖并繼續(xù)執(zhí)行?;蛘弋?dāng)被中斷的時(shí)候也能跳出等待。
- awaitUninterruptibly() 與await類似 但是該方法不會(huì)再等待的過程中響應(yīng)中斷。
- singal() 方法用于喚醒 一個(gè)等待中的線程。singalAll喚醒所有在等待中的線程。
演示代碼如下:
public class ReenterLockCondition implements Runnable {
public static ReentrantLock lock =new ReentrantLock();
public static Condition condtionCondition =lock.newCondition(); //生成一個(gè)Condition對(duì)象
public void run() {
try {
lock.lock();
condtionCondition.await(); //執(zhí)行這里的時(shí)候要求有相關(guān)的重入鎖,在調(diào)用之后會(huì)釋放鎖
System.out.println("Thread is going on");
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
ReenterLockCondition t2=new ReenterLockCondition();
Thread t1=new Thread(t2);
t1.start();
Thread.sleep(2000);
lock.lock();
condtionCondition.signal(); //發(fā)出通告 ,并且要求其先獲得相關(guān)鎖。
lock.unlock(); //釋放重入鎖
}
}
//相關(guān)具體更好的代碼操作可以看ArrayBlockingQueuel例子中的put方法jdk1.7的
代碼執(zhí)行結(jié)果

執(zhí)行結(jié)果
允許多個(gè)線程同時(shí)訪問:信號(hào)量
- 信號(hào)量為多線程協(xié)作提供了更為強(qiáng)大的控制方法,廣義的說是對(duì)鎖的擴(kuò)展。無論是內(nèi)部鎖synchronized還是重入鎖ReentrantLock 。一次都只允許一個(gè)線程訪問一個(gè)資源。而信號(hào)量可以指定多個(gè)線程同時(shí)訪問某一個(gè)資源。
- 構(gòu)造方法如下:
- Semaphore(int permits);
- Semaphore(int permits,boolean fair) ; // 第二個(gè)參數(shù)可以指定時(shí)候公平
- 在使用構(gòu)造信號(hào)量的時(shí)候要指定準(zhǔn)入的信號(hào)量的數(shù)量。同時(shí)可以申請(qǐng)多個(gè)許可
public class SemapDemo implements Runnable {
final Semaphore semp =new Semaphore(5);
public void run() {
try {
semp.acquire(); //獲取信號(hào)量 每次能進(jìn)來5個(gè)線程
Thread.sleep(2000);
System.out.println(Thread.currentThread().getId() + ":done!");
semp.release(); // 如果這里信號(hào)量泄露 沒有釋放 那么會(huì)導(dǎo)致進(jìn)入臨界區(qū)的線程數(shù)量越來越少。直到所有的線程不能再訪問
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//開啟20個(gè)線程 去訪問,會(huì)發(fā)現(xiàn)是5個(gè)線程一組數(shù)據(jù)
ExecutorService executionn= Executors.newFixedThreadPool(20);
final SemapDemo demo =new SemapDemo();
for(int i=0;i<20;i++) {
executionn.submit(demo);
}
}
}

線程結(jié)果