package com.qyc.test;/**
* @CreatAuthor: qiangyuecheng
* @CreatDate: 2021/4/15 11:01 下午
*/
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @ClassName: Test26
* @Description:
* @Author: qiangyuecheng
* @Date: 2021/4/15 11:01 下午
*/
public class Test26 {
public static void main(String[] args) throws InterruptedException {
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
AtomicInteger atomicInteger = new AtomicInteger(0);
new Thread(() -> {
while (true) {
lock.lock();
try {
while (atomicInteger.get() > 0) {
System.out.println("等待消费" + atomicInteger.get());
condition1.await();
}
atomicInteger.getAndIncrement();
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}, "生产者").start();
new Thread(() -> {
while (true) {
lock.lock();
try {
while (atomicInteger.get() == 0) {
System.out.println("等待生产" + atomicInteger.get());
condition2.await();
}
atomicInteger.getAndDecrement();
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}, "消费者").start();
}
}