用三个锁来实现生产者消费者问题
//队列
public class Buffer {
private Queue<String> queue;
private int size = 10;
// 消费者锁
private Object getLock = new Object();
// 生产者锁
private Object addLock = new Object();
private AtomicInteger count = new AtomicInteger(0);
public Buffer() {
queue = new LinkedList<String>();
}
public void add() {
//先通知消费者可以消费了
synchronized (getLock) {
getLock.notifyAll();
}
synchronized (addLock) {
//如果队列未满,则生产
if (queue.size() < size) {
int andIncrement = count.getAndIncrement() % 10;
queue.add(andIncrement + "");
System.out.println("product:" + andIncrement);
} else {
//否则等待消费者唤起
try {
System.out.println("queue is full");
addLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void get() {
//先告诉生产者可以生产了
synchronized (addLock) {
addLock.notify();
}
synchronized (getLock) {
try {
//如果队列为空,等待
if (queue.isEmpty()) {
System.out.println("queue is empty");
getLock.wait();
//否者消费队列
} else {
System.out.println("consume " + Thread.currentThread().getName() + ":" + queue.poll());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Consumer implements Runnable{
private Buffer buffer;
public Consumer(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
buffer.get();
}
}
}
public class Producer implements Runnable {
private Buffer buffer;
public Producer(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
buffer.add();
}
}
}
运行代码
public class Test {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(3);
Buffer buffer = new Buffer();
service.submit(new Producer(buffer));
service.submit(new Consumer(buffer));
service.submit(new Consumer(buffer));
}
}
生产速度大于消费速度
product:0
product:1
product:2
product:3
product:4
product:5
product:6
product:7
product:8
consume pool-1-thread-3:0
consume pool-1-thread-2:1
product:9
product:0
product:1
queue is full
consume pool-1-thread-3:2
consume pool-1-thread-2:3
product:2
product:3
queue is full
消费速度大于生产速度
queue is empty
queue is empty
product:0
consume pool-1-thread-2:0
queue is empty
queue is empty
product:1
consume pool-1-thread-3:1
queue is empty
queue is empty
product:2
consume pool-1-thread-3:2
queue is empty
queue is empty
product:3