ReentrantLock + Condition 实现
package org.example;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumer {
private Queue<String> queue = new LinkedList<>();
private static final Integer BUFFER_SIZE = 3;
private final ReentrantLock lock = new ReentrantLock();
private final Condition producerCondition = lock.newCondition();
private final Condition consumerCondition = lock.newCondition();
public void produce() {
lock.lock();
while (queue.size() >= BUFFER_SIZE) {
try {
producerCondition.await();
} catch (InterruptedException e) {
}
}
queue.add(Thread.currentThread().getName());
System.out.println("[Producer]" + Thread.currentThread().getName());
consumerCondition.signal();
lock.unlock();
}
public void consume() {
lock.lock();
while (queue.isEmpty()) {
try {
consumerCondition.await();
} catch (InterruptedException e) {
}
}
String elem = queue.poll();
System.out.printf("[Consumer] Thread: %s, consume: %s%n\n", Thread.currentThread().getName(), elem);
producerCondition.signal();
lock.unlock();
}
static class Producer implements Runnable {
ProducerConsumer pc;
public Producer(ProducerConsumer pc) {
this.pc = pc;
}
@Override
public void run() {
int times = 3;
while (times-- > 0) {
pc.produce();
}
}
}
static class Consumer implements Runnable {
ProducerConsumer pc;
public Consumer(ProducerConsumer pc) {
this.pc = pc;
}
@Override
public void run() {
int times = 3;
while (times-- > 0) {
pc.consume();
}
}
}
public static void main(String[] args) {
ProducerConsumer producerConsumer = new ProducerConsumer();
Producer producer = new Producer(producerConsumer);
Consumer consumer = new Consumer(producerConsumer);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(producer);
Thread t3 = new Thread(consumer);
Thread t4 = new Thread(consumer);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
还有BlockingQueue实现,也是线程安全的