如问题的名字那样,首先要有个生产者和消费者,所以需要定义两个class来分别描述他们的特点。
/** * 生产者线程类 */ class Producer implements Runnable { /** 持有容器 */ private Can c = null; public Producer(Can c) { this.c = c; } @Override public void run() { while (true) { // 生产一个产品 Production p = new Production(); System.out.println(p + "被生产了。"); // 将产品存入容器 try { c.push(p); } catch (InterruptedException e) { e.printStackTrace(); } } } }
/** * 消费者线程类 */ class Consumer implements Runnable{ /** 持有容器 */ private Can c = null; public Consumer(Can c) { this.c = c; } @Override public void run() { while (true) { // 从容器取出一个产品 Production p = null; try { p = c.pop();// 消费一个产品 System.out.println(p + "被毁灭了。"); } catch (InterruptedException e) { e.printStackTrace(); } } } }
紧接着,生产者和消费者是通过“产品”联系起来,所以还需要定义一个描述“产品”的POJO。
/** * 产品的实体类 */ class Production { /** 识别No. */ private int no = 0; private static int counter = 0; public Production() { no = counter++; } public String toString() { return no + "号产品"; } }
最后是临时容纳“产品”的容器,它应该通过栈来实现,同时它的实例还被许多生产者实例和消费者实例,这些实例都象征着一个线程。
/** * 用栈实现的容器类 */ class Can { /** 栈顶指针 */ private int pointer = 0; /** 内部持有对象的数组 */ private Production[] productions = {null, null, null, null, null, null}; /** 压入一个元素 */ public synchronized void push(Production p) throws InterruptedException { while (pointer == 6) { wait(); } productions[pointer++] = p;
System.out.println(p + "被放入容器。"); notifyAll(); } /** 弹出一个元素 */ public synchronized Production pop() throws InterruptedException { while (pointer == 0) { wait(); } Production p = productions[--pointer];
System.out.println(p + "从容器取出。"); notifyAll(); return p; } }
演示一下
package ProducerConsumerProblem.copy; /** * 生产者消费者问题的演示类 */ class ProblemDemo { public static void main(String[] args) { Can c = new Can(); Producer producer = new Producer(c); Consumer consumer = new Consumer(c); new Thread(producer).start(); new Thread(producer).start(); new Thread(producer).start(); new Thread(producer).start(); new Thread(consumer).start(); } }
结果
1号产品被生产了。
2号产品被生产了。
3号产品被生产了。
0号产品被生产了。
1号产品被放入容器。
4号产品被生产了。
1号产品从容器取出。
0号产品被放入容器。
1号产品被毁灭了。
5号产品被生产了。
3号产品被放入容器。
6号产品被生产了。
2号产品被放入容器。
7号产品被生产了。
6号产品被放入容器。
8号产品被生产了。
5号产品被放入容器。
9号产品被生产了。
5号产品从容器取出。
5号产品被毁灭了。
4号产品被放入容器。
……
……
……