使用Condition可以实现线程按序交替
package org.meng.juc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @ClassName: ProducerAndConsumer
* @Description: while 解决虚假唤醒问题 -> wait()方法需要在while循环中使用
* @Author: MengMeng
* @Date: 2021/1/17 1:40 下午
* @Version: v1.0
*/
public class ProducerAndConsumer {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Productor productor = new Productor(clerk);
Consumer consumer = new Consumer(clerk);
new Thread(productor,"生产者 A").start();
new Thread(consumer,"消费者 B").start();
new Thread(productor,"生产者 C").start();
new Thread(consumer,"消费者 D").start();
}
static class Clerk {
private int product = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void get() {
lock.lock();
try {
// while 解决虚假唤醒问题 -> wait()方法需要在while循环中使用
while (product >= 10) {
System.out.println("产品已满");
try {
condition.await();
} catch (Exception e) {
}
}
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 (Exception e) {
}
}
System.out.println(Thread.currentThread().getName() + ":" + --product);
condition.signalAll();
}finally {
lock.unlock();
}
}
}
static 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++) {
clerk.get();
}
}
}
static 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();
}
}
}
}