ReentrantLock的搭檔:Condition
ReentrantLock通過Condition對自身進(jìn)行增強(qiáng)
用于Lock控制線程執(zhí)行順序
代碼如下:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 模塊:【Condition 和 重入鎖組合應(yīng)用】
* <p>
* 開發(fā): Bruce.Liu By 2018/8/23 下午8:31 Create
*/
public class ReentrantLockCondition implements Runnable {
private static ReentrantLock lock = new ReentrantLock();
private static Condition condition = lock.newCondition();
@Override
public void run() {
try {
lock.lock();
System.err.println("Thread is going on await before");
condition.await();//當(dāng)前線程掛起-等待
System.err.println("Thread is going on await after");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
ReentrantLockCondition rlm = new ReentrantLockCondition();
Thread t1 = new Thread(rlm);
t1.start();
TimeUnit.SECONDS.sleep(2);
System.err.println("Main Lock Before");
lock.lock();
System.err.println("Main Lock After");
condition.signal();//喚醒t1線程
lock.unlock();//釋放鎖
/**
* 執(zhí)行結(jié)果:
* 1.Thread is going on await before
* 2.Main Lock Before
* 3.Main Lock After
* 4.Thread is going on await after
*/
}
}
代碼解讀
A. 上述代碼中存在兩個線程
- main 函數(shù)啟動的主線程
- 主線線程創(chuàng)建的Thread t1 線程
B. main函數(shù)啟動時會創(chuàng)建t1線程,為了讓主線程等待t1執(zhí)行使用了
TimeUnit.SECONDS.sleep(2);
C. t1線程加鎖,輸出打印執(zhí)行到 condition.await();將當(dāng)前t1線程線程掛起
System.err.println("Thread is going on await before");
condition.await();//當(dāng)前線程掛起-等待
D. 主線程等待時間2s到期后,繼續(xù)執(zhí)行代碼打印輸出
直到condition.signal();//喚醒t1線程
condition.signal();//喚醒t1線程
參考:《實(shí)戰(zhàn) Java 高并發(fā)程序設(shè)計(jì)》這本書。