/**
* Producer Thread will keep producing values for Consumer
* to consumer. It will use wait() method when Queue is full
* and use notify() method to send notification to Consumer
* Thread.
*
* @author WINDOWS 8
*/
class Producer extends Thread {
private Queue<Object> queue;
private int maxSize;
public Producer(Queue<Object> queue, int maxSize, String name) {
super(name);
this.queue = queue;
this.maxSize = maxSize;
}
@SneakyThrows
@Override
public void run() {
while (true) {
// 同步代码段
synchronized (queue) {
while (queue.size() == maxSize) {
try {
System.out.println("Queue is full, " + "Producer thread waiting for " + "consumer to take something from queue");
// 由于条件不满足,生产阻塞
queue.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 生产条件满足情况下,生产产品
Random random = new Random();
int i = random.nextInt();
System.out.println("线程(" + Thread.currentThread().getName() + ")生产了一件产品: " + i + ";当前剩余商品" + queue.size() + "个");
queue.add(i);
queue.notifyAll();
Thread.sleep(1000);
}
}
}
}
消费者
/**
* Consumer Thread will consumer values form shared queue.
* It will also use wait() method to wait if queue is
* empty. It will also use notify method to send
* notification to producer thread after consuming values
* from queue.
*
* @author WINDOWS 8
*/
class Consumer extends Thread {
private Queue<Object> queue;
private int maxSize;
public Consumer(Queue<Object> queue, int maxSize, String name) {
super(name);
this.queue = queue;
this.maxSize = maxSize;
}
@SneakyThrows
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
System.out.println("Queue is empty," + "Consumer thread is waiting" + " for producer thread to put something in queue");
try {
queue.wait();
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("线程(" + Thread.currentThread().getName() + ")消费了一件商品: " + queue.remove() + ";当前剩余商品" + queue.size() + "个");
queue.notifyAll();
Thread.sleep(1000);
}
}
}
}
测试
import lombok.SneakyThrows;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class ProducerConsumerInJava {
public static void main(String args[]) {
Queue<Object> queue = new LinkedList<Object>();
Thread producer = new Producer(queue, 1, "producer");
Thread consumer1 = new Consumer(queue, 1, "consumer1");
Thread consumer2 = new Consumer(queue, 1, "consumer2");
Thread consumer3 = new Consumer(queue, 1, "consumer3");
Thread consumer4 = new Consumer(queue, 1, "consumer4");
producer.start();
consumer1.start();
consumer2.start();
consumer3.start();
consumer4.start();
}
}
生产者/** * Producer Thread will keep producing values for Consumer * to consumer. It will use wait() method when Queue is full * and use notify() method to send notification to Consumer * Thread. * * @author WINDOWS 8 */class Producer extends Thre