本文是看视频学习笔记,若有错误请指正!
生产者消费者案例的lock写法
其中涉及到了Condition的用法,简答的介绍一下:
1.Condition接口描述了可能会与锁相关的条件变量,这些变量在用法上与使用Object.wait访问的隐式监视器类似,但提供了更强大的功能。需要特别之处的是,单个lock可能会与多个Condition对象关联,为了避免兼容性问题,Condition方法的名称与对应的Object版本中的不同。
2.在Condition对象中,与wait,notify,notifyAll方法对应的分别是await,signal,signalAll
3.Condition实例实质上被绑定到一个锁上。要为特定的Lock实例获得Condition,使用newCondition()方法即可。
具体代码:
public class TestProductorAndCustomerForLock {
public static void main(String[] args){
Clerk clerk = new Clerk();
Productor productor = new Productor(clerk);
Customer customer = new Customer(clerk);
new Thread(productor,"productor A").start();
new Thread(productor,"productor B").start();
new Thread(customer,"customer A").start();
new Thread(customer,"customer B").start();
}
}
class Clerk {
private int productor = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
//进货
public void get() {
lock.lock();
try {
while (productor >= 1) {
System.out.println("产品已满!");
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ":" + ++productor);
condition.signalAll();
}finally {
lock.unlock();
}
}
//卖货
public void sale() {
lock.lock();
try {
while (productor <= 0) {
System.out.println("缺货!");
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ":" + --productor);
condition.signalAll();
}finally {
lock.unlock();
}
}
}
class Productor implements Runnable{
private Clerk clerk;
public Productor(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.get();
}
}
}
class Customer implements Runnable{
private Clerk clerk;
public Customer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
clerk.sale();
}
}
}
运行结果: