2 Star 0 Fork 0

20155207wxc/besti-java-20155207wxc

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Clerk.java 1.32 KB
一键复制 编辑 原始数据 按行查看 历史
lnaswxc 提交于 2017-06-01 14:37 . 实验五
package cc.openhome;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Clerk {
private int product = -1;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void setProduct(int product) throws InterruptedException {
lock.lock();
try {
waitIfFull();
this.product = product;
System.out.printf("生产者设定 (%d)%n", this.product);
condition.signal();
} finally {
lock.unlock();
}
}
private void waitIfFull() throws InterruptedException {
while (this.product != -1) {
condition.await();
}
}
public int getProduct() throws InterruptedException {
lock.lock();
try {
waitIfEmpty();
int p = this.product;
this.product = -1;
System.out.printf("消费者取走 (%d)%n", p);
condition.signal();
return p;
} finally {
lock.unlock();
}
}
private void waitIfEmpty() throws InterruptedException {
while (this.product == -1) {
condition.await();
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/lnaswxc/besti-java-20155207wxc.git
git@gitee.com:lnaswxc/besti-java-20155207wxc.git
lnaswxc
besti-java-20155207wxc
besti-java-20155207wxc
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385