具体代码如下:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class ProducerConsumerTest {
private static final int CAPACITY = 5;
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
Producer producer = new Producer(queue, CAPACITY);
Thread producer1 = new Thread(producer,"生产者1");
Thread producer2 = new Thread(producer,"生产者2");
Consumer consumer = new Consumer(queue, CAPACITY);
Thread consumer1 = new Thread(consumer,"消费者1");
Thread consumer2 = new Thread(consumer,"消费者2");
Thread consumer3 = new Thread(consumer,"消费者3");
producer1.start();
producer2.start();
consumer1.start();
consumer2.start();
consumer3.start();
}
/**
* 生产者
*/
public static class Producer implements Runnable{
private Queue<Integer> queue;
int maxSize;
int i = 1;
public Producer(Queue<Integer> queue, int maxSize) {
this.queue = queue;
this.maxSize = maxSize;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.size() == maxSize) {
try {
System.out.println(Thread.currentThread().getName() + "生产达到最大值");
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("生产第:" + i + "个产品");
queue.offer(i++);
queue.notifyAll();
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 消费者
*/
public static class Consumer implements Runnable {
private Queue<Integer> queue;
int maxSize;
public Consumer(Queue<Integer> queue, int maxSize) {
this.queue = queue;
this.maxSize = maxSize;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
try {
System.out.println(Thread.currentThread().getName() + "消费完产品");
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int i = queue.poll();
System.out.println("生产第:" + i + "个产品");
queue.notifyAll();
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
可以研究一下实现的过程,这只是最简单的实现.
网友评论