在使用Lock进行解决线程同步问题时,会存在使用Object的wait()和sleep()方法异常的问题.
而jdk也提供了Condition对应于Objcet的wait(),notify()和notifyAll()方法提供了await(),signal()和signalAll()方法.
Condition实例实质上是需要绑定到一个锁上.所以需要为Lock实例获得Condition实例,需要使用Lock的newCondition()方法.
下面是案例(同时解决了虚假唤醒)
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author 嘿嘿嘿1212
* @version 1.0
* @date 2020/1/31 19:48
*/
//主方法
public class TestProductorAndConsumerForLock {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer pro = new Producer(clerk);
Consumer cus = new Consumer(clerk);
new Thread(pro, "生产者A").start();
new Thread(cus, "消费者B").start();
new Thread(pro, "生产者C").start();
new Thread(cus, "消费者D").start();
}
}
//仓库类
class Clerk {
private int product = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
//进货
public void get() {
lock.lock();
try {
while (product >= 1) {
System.out.println("仓库已满");
try {
//在仓库已满时才进行等待
condition.await();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + ":" + ++product);
//当仓库内存在货物时,通知线程可以进行卖货了
condition.signalAll();
} finally {
lock.unlock();
}
}
//卖货
public void sale() {
lock.lock();
try {
while (product <= 0) {
System.out.println("缺货");
try {
//在仓库缺货时才进行等待
condition.await();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + ":" + --product);
//通知线程可以进行进货了,存在空位
condition.signalAll();
} finally {
lock.unlock();
}
}
}
//生产者类
class Producer implements Runnable {
private Clerk clerk;
public Producer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
//存在延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
clerk.get();
}
}
}
//消费者类
class Consumer implements Runnable {
private Clerk clerk;
public Consumer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
clerk.sale();
}
}
}