ReentrantLock的搭档:Condition
ReentrantLock通过Condition对自身进行增强
用于Lock控制线程执行顺序
代码如下:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 模块:【Condition 和 重入锁组合应用】
* <p>
* 开发: 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();//当前线程挂起-等待
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();//释放锁
/**
* 执行结果:
* 1.Thread is going on await before
* 2.Main Lock Before
* 3.Main Lock After
* 4.Thread is going on await after
*/
}
}
代码解读
A. 上述代码中存在两个线程
- main 函数启动的主线程
- 主线线程创建的Thread t1 线程
B. main函数启动时会创建t1线程,为了让主线程等待t1执行使用了
TimeUnit.SECONDS.sleep(2);
C. t1线程加锁,输出打印执行到 condition.await();将当前t1线程线程挂起
System.err.println("Thread is going on await before");
condition.await();//当前线程挂起-等待
D. 主线程等待时间2s到期后,继续执行代码打印输出
直到condition.signal();//唤醒t1线程
condition.signal();//唤醒t1线程
参考:《实战 Java 高并发程序设计》这本书。
网友评论