用多線程實現一個生產者消費者模型,滿足如下條件:
1. 先生產後消費,不生產不消費
2. 要求最多生產5個產品,超過5個則不能繼續生產,低於0個則不能消費
3. 採用多線程實現
相關Java程序如下。
package cn.edu.lcudcc; import java.util.LinkedList; import java.util.Queue; public class ProducerConsumer { private static final int MAX_SIZE = 5; private final Queue<Integer> queue = new LinkedList<>(); class Producer extends Thread { @Override public void run() { int value = 0; while (true) { synchronized (queue) { while (queue.size() >= MAX_SIZE) { try { System.out.println("隊列滿,生產者 " + Thread.currentThread().getName() + " 等待"); queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("生產者 " + Thread.currentThread().getName() + " 生產了產品:" + value); queue.offer(value++); queue.notifyAll(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } class Consumer extends Thread { @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 value = queue.poll(); System.out.println("消費者 " + Thread.currentThread().getName() + " 消費了產品:" + value); queue.notifyAll(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public static void main(String[] args) { ProducerConsumer pc = new ProducerConsumer(); pc.new Producer().start(); pc.new Consumer().start(); } }