package com.wyz.juc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 使用 Lock 替换synchronized 实现生产者和消费者
*
* Condition
* Condition 接口描述了可能会与锁有关联的条件变量。这些变量在用
* 法上与使用 Object.wait 访问的隐式监视器类似,但提供了更强大的
* 功能。需要特别指出的是,单个 Lock 可能与多个 Condition 对象关
* 联。为了避免兼容性问题,Condition 方法的名称与对应的 Object 版
* 本中的不同。 在 Condition 对象中,与 wait、notify 和 notifyAll 方法对应的分别是
* await、signal 和 signalAll。 Condition 实例实质上被绑定到一个锁上。要为特定 Lock 实例获得
* Condition 实例,请使用其 newCondition() 方法。
* @author WangChong
*/
public class TestProductorAndConsumerForLock {
public static void main(String[] args) {
ClerkLock clerkLock = new ClerkLock();
ProductorLock productor = new ProductorLock(clerkLock);
ConsumerLock consumer = new ConsumerLock(clerkLock);
new Thread(productor, "生产者A").start();
new Thread(consumer, "消费者B").start();
new Thread(productor, "生产者C").start();
new Thread(consumer, "消费者D").start();
}
}
//店员
class ClerkLock {
private int product = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
//进货
public void get() {
lock.lock();
try {
while (product >= 1) {//为了避免虚假唤醒问题 wait()应该总是使用在循环中
System.out.println("产品已满");
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ": " + ++product);
condition.signalAll();
} finally {
lock.unlock();
}
}
//卖货
public synchronized void sale() {
lock.lock();
try {
while (product <= 0) {
System.out.println("缺货");
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ": " + --product);
condition.signalAll();
} finally {
lock.unlock();
}
}
}
//生产者
class ProductorLock implements Runnable {
private ClerkLock clerkLock;
public ProductorLock(ClerkLock clerkLock) {
this.clerkLock = clerkLock;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(200);
clerkLock.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
class ConsumerLock implements Runnable {
private ClerkLock clerkLock;
public ConsumerLock(ClerkLock clerkLock) {
this.clerkLock = clerkLock;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
clerkLock.sale();
}
}
}
juc学习备忘录10--使用Lock 方式实现生产者消费者案例
最新推荐文章于 2024-05-06 20:09:14 发布