Java Condition
Condition
condition是相对synchronized的线程通信的更加灵活的方式。
用法
新建锁lock
-->建立condition, lock.newCondition();
-->在锁住的代码中使用condition.await()和condition.signal()/condition.signalAll()来等待和唤醒(synchronized对应的方法就是wait()和notify()/notifyAll()
以下是完整示例:
package JavaCore.MultiThread.advanced.Lock.ThreadCorrespondence.ProducerAndConsumer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*******************************************************************************
* @Copyright (C), 2018-2019,github:Swagger-Ranger
* @FileName: Market
* @Author: liufei32@outlook.com
* @Date: 2019/3/10 15:31
* @Description: 生产者消费者模型地市场,即生成者与消费者线程通信地中间类
* @Aha-eureka:
*******************************************************************************/
public class Market_Condition implements Market_Interface {
private int product_count;
private final int MAXIMUM = 10;
Lock lock = new ReentrantLock();
Condition pc = lock.newCondition();
Condition cc = lock.newCondition();
public void produce() {
lock.lock();
//注意这里判断库存情况必须用while而不能用if,在唤醒后while将继续判断直到不满足即小于库存容量才会生产,而if不会再次去判断库存就直接生产
while (this.product_count >= MAXIMUM) {
System.out.println("库存饱和,生产者: " + Thread.currentThread().getName() + ",请停止生产...");
try {
pc.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
product_count++;
System.out.println("生产者: " + Thread.currentThread().getName() + "生成并推送到库存,当前库存:" + product_count);
cc.signal();
lock.unlock();
}
public void consume() {
lock.lock();
while (this.product_count <= 0) {
System.out.println("库存告罄,消费者:" + Thread.currentThread().getName() + "正在等待,请生产者开始生产...");
try {
cc.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
product_count--;
System.out.println("消费者:" + Thread.currentThread().getName() + "消费成功,当前库存:" + product_count);
pc.signal();
}
}
本博客为Swagger-Ranger的笔记分享,文中源码地址: https://github.com/Swagger-Ranger
欢迎交流指正,如有侵权请联系作者确认删除: liufei32@outlook.com
posted on 2019-04-08 13:21 Swagger-Ranger 阅读(328) 评论(0) 编辑 收藏 举报