public class ProduceAndCoustomer {
private static final ReentrantLock lock = new ReentrantLock();
private static final ReentrantLock lock2 = new ReentrantLock();
private static Queue<Integer> queue = new LinkedList<>();
private final static Condition condition1 = lock.newCondition();
private final static Condition condition3 = lock2.newCondition();
private static volatile AtomicInteger num = new AtomicInteger(0);
private static volatile int max = 1000;
static class Produce1 implements Runnable {
private String name;
public Produce1(String name) {
this.name = name;
}
@Override
public void run() {
while (true) {
lock.lock();
put();
lock.unlock();
}
}
public void put() {
while (num.get() == max) {
try {
System.out.println("队列满了,生产者暂停生产");
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(1);
int andIncrement = num.getAndIncrement();
if (andIncrement < max) {
condition1.signalAll();
}
System.out.println(name + "进行生产,");
System.out.println("队内总的元素为:" + num.get());
if (num.get()==max){
lock2.lock();
condition3.signalAll();
lock2.unlock();
}
}
}
static class Coustomer1 implements Runnable {
private String name;
public Coustomer1(String name) {
this.name = name;
}
@Override
public void run() {
while (true) {
lock2.lock();
take();
lock2.unlock();
}
}
public int take() {
int andDecrement = 0;
int poll = 0;
try {
while (num.get() == 0) {
System.out.println("队列空了,消费者暂停消费");
condition3.await();
}
poll = queue.poll();
andDecrement = num.getAndDecrement();
if (andDecrement > 1) {
condition3.signalAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (andDecrement == 0) {
try {
lock.lock();
condition1.signalAll();
lock.unlock();
} finally {
lock.lock();
}
}
System.out.println(name + "进行消费");
System.out.println("队内总元素数量为:" + num.get());
return poll;
}
}
public static void main(String[] args) throws InterruptedException {
new Thread(new Produce1("生产者1")).start();
new Thread(new Produce1("生产者2")).start();
new Thread(new Coustomer1("消费者1")).start();
new Thread(new Coustomer1("消费者2")).start();
}
}